[LeetCode] Remove Element
Thought:
Iterate from the end of the array, if we find a match we exchange the current value and the len-1 index value, and then update the len.
Code:
public class Solution {
public int removeElement(int[] A, int elem) {
int len = A.length;
for(int i = A.length - 1; i >= 0; i--){
if(A[i] == elem){
A[i] = A[len - 1];
len--;
}
}
return len;
}
}
No comments:
Post a Comment