5/30/2014

24. Remove Duplicates from Sorted Array

public class Solution {
    public int removeDuplicates(int[] A) {
        if (A.length==0) return 0;
        if (A.length==1) return 1;
       
        int p=0;
        int q=1;
       
        while (p<A.length && q<A.length) {
            if (A[q]==A[p]) q++;
            else {
                p++;
                A[p] = A[q];
                q++;
            }
        }
       
        return p+1;
    }
}

2 条评论:

  1. 1. Two pointers;
    2. 如果A[q]!=A[p],q++.
    3. 找到第一个A[q]!=A[p],令A[p+1]=A[q].

    回复删除
  2. 更正:
    2. 如果A[q]==A[p], q++.

    回复删除