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-place with 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 ofnums
being1, 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 ofnums
being modified to0
, 0, 1, 1, 2, 3 and 3 respectively. It doesn't matter what values are set beyond the returned length.
Solution:
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// Author: Huahua class Solution { public: int removeDuplicates(vector<int>& nums) { const int n = nums.size(); if (n <= 2) return n; int index = 1; int len = 1; int last = nums[0]; while (index < n) { int count = 1; while (index < n && nums[index] == last) { ++count; ++index; } if (count >= 2) nums[len++] = last; if (index < n) { last = nums[index++]; nums[len++] = last; } } return len; } }; |