Remove Duplicates from Sorted Array II, Leetcode 解题笔记

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 {
    public int removeDuplicates(int[] A) {
        int len = A.length;
        if(len <=2 ) return len;
        int index = 2;
        for(int i = index; i < len; i++){
            if(A[i] != A[index-2]){
                A[index] = A[i];
                index++;
            }
        }
        return index;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s