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 nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1122 and 3. It doesn't matter what you leave beyond the new length.

 

题目大意:给定一个排好序的数组,有重复元素,要求返回新数组长度,新数组中重复元素只能出现两次,新长度后面的是什么无所谓。

解题思路,从前向后遍历,记录一个newLen变量,重复元素记录两次,非重复元素就直接copy到新数组应有的下标处。

    public int removeDuplicates(int[] nums) {

        if(nums==null||nums.length==0){

            return 0;

        }

        int newLen=0;

        for(int i=0;i<nums.length;i++){

            int pos=i;

            nums[newLen++]=nums[i];

            while(i<nums.length-1&&nums[i]==nums[i+1]){

                i++;

            }

            if(pos==i)

                continue;

            nums[newLen++]=nums[i];

        }

        return newLen;

    }

 

你可能感兴趣的:(LeetCode)