Basic idea of my code: variable len is used as a index representing where to put an unique element; once an unique, or differernt element is found, set A[len] to be this value. Since it is a sorted array, we can solve this problem in this way. Totally, time complexity should be O(n).
public class Solution {
public int removeDuplicates(int[] A) {
if(A == null) return 0;
if (A.length <= 1) return A.length ;
int crntPre = A[0];
int len = 1;
for(int i = 1; i < A.length; i ++){
if(crntPre != A[i]){
// set element at swapTo to be A[i]
A[len] = A[i];
len ++;
crntPre = A[i];
}
}
return len;
}
}
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, July 9, 2014
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment