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],
Your function should return length = 5, and A is now [1,1,2,2,3]

public class Solution2 {

    public static int remove(int[] arr) {
        if(arr == null || arr.length == 0)
            return 0;
        if(arr.length <= 2)
            return arr.length;
         
        // 以index指针为基准,和i指针作比较   
        int index = 2;
        for(int i = 2; i < arr.length; ++i) {
            if(arr[i] != arr[index - 2]) {
                arr[index++] = arr[i];
            }
        }
        return index;
    }
}

你可能感兴趣的:(Remove Duplicates from Sorted Array II)