Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most _twice_and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-placewith O(1) extra memory.
Example 1:
Given
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
respectively.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given
nums
=
[0,0,1,1,1,1,2,3,3]
,
Your function should return length =
7
, with the first seven elements of
nums
being modified to
0
,
0
,
1
,
1
,
2
,
3
and
3
respectively.
It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
//
nums
is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to
nums
in your function would be known by the caller.
// using the length returned by your function, it prints the first
len
elements.
for (int i = 0; i
<
len; i++) {
print(nums[i]);
}
LeetCode 上的一个对于Remove Duplicates from Sorted Array I,II 通用的答案:(k = 1, or, k = 2)
O(n) time, and O(1) space
we need a count variable to keep how many times the duplicated element appears, if we encounter a different element, just set counter to 1, if we encounter a duplicated one, we need to check this count, if it is already k, then we need to skip it, otherwise, we can keep this element.
publicintremoveDuplicates(int[] nums) {int i =0;for (int n : nums)if (i <2|| n != nums[i-2]) nums[i++] = n;return i; }
Could be applied to k - general solution
classSolution {publicintremoveDuplicates(int[] nums) {returnremoveDuplicates(nums,2); }publicintremoveDuplicates(int[] nums,int k) {int i =0;for (int n : nums) {if (i < k || n != nums[i-k]) { nums[i++] = n; } }return i; }}
Another implementation:
classSolution {publicintremoveDuplicates(int[] nums) {returnremoveDuplicates(nums,2); }privateintremoveDuplicates(int[] nums,int k) {// if array size is less than k then return the sameif(nums.length< k) {returnnums.length; }int i, j;// start from index kfor(i = k, j = k ; j <nums.length; j++) {if(nums[i - k] != nums[j]) { nums[i++] = nums[j]; } }return i; }}