Leetcode——80. Remove Duplicates from Sorted Array II

来源:互联网 发布:mac 复制照片到u盘 编辑:程序博客网 时间:2024/06/07 02:52

题目

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.

https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

解答

这个解答太精秒了!!

class Solution {public:    int removeDuplicates(vector<int>& nums) {        int i=0;        for(int j=0;j<nums.size();j++)        {            if(i<2||nums[j]>nums[i-2])            {                nums[i]=nums[j];                i++;            }        }        return i;    }};

参考:https://discuss.leetcode.com/topic/17180/3-6-easy-lines-c-java-python-ruby

Just want to confirm, this solution can be easily generalized to "at most K duplicates", right?int removeDuplicates(vector<int>& nums, int k) {    int i = 0;    for (int n : nums)        if (i < k || n > nums[i-k])            nums[i++] = n;    return i;}
0 0
原创粉丝点击