Happiness is more than pleasure without pain

你只有非常努力,才能看起来毫不费力

导航

Remove Duplicates from Sorted Array II

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],

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

public class Solution {

    public int removeDuplicates(int[] A) {
    int i,j=1,first = 0;//快慢指针,first判断是否是只重复一次。
    if(A==null)return 0;
    if(A.length<=1)return A.length;
    for( i=1;i<A.length;i++){    
    if(A[i]!=A[i-1]){
    A[j++]=A[i];
    first=0;
    }
    else if(first==0){    
        A[j++]=A[i];
        first=1;
        }
    }   


    return j;        
    }
}


更简洁的:
public class Solution {
    public int removeDuplicates(int[] A) {
    int i,j=2;//快慢指针
    if(A==null)return 0;
    if(A.length<=2)return A.length;
    for( i=2;i<A.length;i++){    
    if(A[i]!=A[j-2]) A[j++]=A[i];
    }
    return j;        
    }
}

posted on 2014-10-17 12:31  believer  阅读(148)  评论(0)    收藏  举报