Remove Duplicates from Sorted Array II

Problem:
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.

Analysis:
Similar to Remove Duplicates from Sorted Array They can have template for allowing k duplicates for each number. 
这种题在面试中死都想不出来。。。。太特殊了,得背。而且这么短的题 不太可能出现在on site。
Solution:

class Solution {
    public int removeDuplicates(int[] nums, int k) {
        int i = 0;
        for (int n: nums) {
            if (i < k || n != nums[i - k]) {
                nums[i++] = n;
            }
        }
        return i;
    }
}

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array