80. Remove Duplicates from Sorted Array II

来源:互联网 发布:爱编程 微信小程序 编辑:程序博客网 时间:2024/06/07 21:19

题目

可以重复一次的去重操作

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.

代码

public class Solution {// first sort nums     //second, assume nums[1,2,...i-2,i-1,i] have filtered duplicates        // nums[j,j+1,...] is filtering(j>=i), j-i is the number of filtered elements        // if (nums[j]>nums[i-2]) then we can put nums[j] at nums[i+1]        // else nums[j]<=nums[i-2] and because we have two elements(nums[i-1], nums[i]), so filter them.        public int RemoveDuplicates(int[] nums)        {            Array.Sort(nums);            int i = 0;            foreach (var n in nums)            {                if (i < 2 || n > nums[i - 2])                    nums[i++] = n;            }            return i;        }}
原创粉丝点击