public class Solution {
public int removeElement(int[] A, int elem) {
if(A.length == 0) return A.length;
int startIdx = 0, endIdx = A.length - 1, newLen = A.length;
while(startIdx <= endIdx){
while(endIdx >= 0 && endIdx!= startIdx && A[endIdx]==elem) {
endIdx --;
newLen --;
}
if(endIdx < 0){
return newLen;
}
if(A[startIdx] == elem){
A[startIdx] = A[endIdx];
endIdx --;
newLen --;
}
startIdx ++;
}
return newLen;
}
}
Hello, welcome to Yizhe's Blog. I am Yizhe Liu, graduated from University of Arizona, with Master degree, major in Electrical and Computer Engineering. Actually, I am software guy. In my blog, many posts are about the Leetcode questions. I will post my ideas and implementations, which are accepted by Leetcode. If you have different opinions, please leave comment. I am happy to discuss with you. So lets start rocking them!!!
Wednesday, August 20, 2014
Remove Element
Quite easy one. The tricky part may be how to remove element instances so that the whole algorithm takes O(n) time, while in-place. One hint given to us is very helpful: "The order of elements can be changed". So I think that just replace the element we need to remove with a different one, which can be found from end of array. And algorithm stops until start index, or can be also called insert index, meets end index. All elements are traversed just once, so time should be O(n)
Labels:
LeetCode
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment