Wednesday, July 16, 2014

Remove Duplicates from Sorted Array I & II

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].
public class Solution {
    //Time: O(n)  Space: O(1)
    public int removeDuplicates(int[] A) {
        if (A == null || A.length == 0) {
            return 0;
        }
        
        int length = 1;
        for (int i = 1; i < A.length; i++) {
            if (A[i] != A[i - 1]) {
                A[length++] = A[i];
            }
        }
        return length;
    }
}

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3],

Your function should return length = 5, and A is now [1,1,2,2,3].

额外用一个变量记录出现次数
public class Solution {
    //Time: O(n)  Space: O(1)
    public int removeDuplicates(int[] A) {
        if (A == null || A.length == 0) {
            return 0;
        }
        
        int val = A[0];
        int count = 1;
        int length = 1;
        for (int i = 1; i < A.length; i++) {
            if (A[i] != A[i - 1]) {
                A[length++] = A[i];
                val = A[i];
                count = 1;
            } else {
                if (count == 1) {
                    A[length++] = A[i];
                }
                count++;
            }
        }
        return length;
    }
}

假如需要把所有重复都删除呢?
public int remove(int[] A) {  
      int length = 0;  
      int val = A[0];  
      int count = 1;  
      for (int i = 1; i &lt; A.length; i++) {  
           if (A[i] == val) {  
                count++;  
           } else {  
                if (count == 1) {  
                     A[length++] = val;     
                }  
                count = 1;  
                val = A[i];  
           }  
      }  
      //额外检查最后一个元素  
      if (count == 1) {  
           A[length++] = val;  
      }  
      return length;  
}  

No comments:

Post a Comment