Remove Duplicates from Sorted Array II
Problem:
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
What if duplicates are allowed at most twice?
For example,
Given sorted array nums =
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.
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; } }
评论
发表评论