This is my first version of code for this problem. The code below should be easy to understand. Actually, I think some variables are redundant. If these variables are removed, code gets improved, then we can finish this problem in-place. I will update the improvement sooner or later.
public class Solution {
public int removeDuplicates(int[] A) {
int ALen = A.length;
if (A == null || ALen == 0) return 0;
if (ALen < 3) return ALen;
int i = 1;
int count = 1;
int num = A[0];
int currentNum;
ArrayList<Integer> arrA = new ArrayList<Integer>();
arrA.add(num);
while(i < ALen){
currentNum = A[i];
if(num == currentNum && count < 2 ){
count++;
arrA.add(currentNum);
}
else{
if(num != currentNum){
num = currentNum;
count = 1;
// length ++;
arrA.add(num);
}// The else case must be "count = 2", no need to deal with it, just move index to next
}
i ++;
}
i = 0;
while(i<ALen){
if(i < arrA.size()){
A[i] = arrA.get(i);
}
i ++;
}
return arrA.size();
}
}
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!!!
Thursday, May 29, 2014
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment