Monday, February 25, 2013

[LeetCode] Remove Duplicates from Sorted Array

Thought:
It is very easy..
Just scan the array, if the current value = index value, let the length - 1.
If the current value != index value, copy it into index's next place, and update index.

Code:
public class Solution {
    public int removeDuplicates(int[] A) {
        int index = 0;
        int len = A.length;
       
        if(A.length <= 1) return len;
       
        for(int i = 1; i < A.length; i++){
            if(A[i] == A[index]){
                len--;
            }else{
                A[++index] = A[i];
            }
        }
        return len;
    }
}

No comments:

Post a Comment