[LeetCode] 80. Remove Duplicates from Sorted Array II

来源:互联网 发布:设计发型软件 编辑:程序博客网 时间:2024/05/29 04:30

【原题】
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 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.
【解释】
作为删除数组中重复元素的进化版,要求最后目标数组中最多只能有每个元素最多重复两次。
【思路】
在Remove Duplicates from Sorted Array一题中,我们只需要记录目标数组下一个该插入的位置,让后续符合要求的元素插入该位置即可。利用同样的思想,只是在比较的时候不是和前一个元素比较,而是前两个元素。

public int removeDuplicates(int[] nums) {        int pos=0;//记录下一个插入的位置        for(int i=0;i<nums.length;i++){            if(i<2||nums[i]>nums[pos-2])//和前两个元素比较                nums[pos++]=nums[i];        }        return pos;//犹豫pos从零开始,所以最后即为目标数组的长度    }
阅读全文
0 0
原创粉丝点击