Wednesday, December 31, 2014

Leetcode 80: Remove Duplicates from Sorted Array II

Problem:
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]
Analysis:
As duplicates are allowed at most twice, the first thought is to compare the current element with the
previous two elements. However, we must remember that the array is a sorted array, which implies
that if current element equals to the second previous element, it must equal to the first previous one.
If not equal, current element can be added to the list.

Code:

public class Solution {
    public int removeDuplicates(int[] A) {
       if(A.length<=2){
           return A.length;
       }
       int tail=2;
       for(int i=2;i<A.length;i++){
           if(A[i]!=A[tail-2]){
               A[tail++]=A[i];
           }
       }
       return tail;
    }
}

No comments:

Post a Comment