|
| 1 | +# 80. Remove Duplicates from Sorted Array II |
| 2 | + |
| 3 | +- Difficulty: Medium. |
| 4 | +- Related Topics: Array, Two Pointers. |
| 5 | +- Similar Questions: Remove Duplicates from Sorted Array. |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +Given a sorted array **nums**, remove the duplicates **in-place** such that duplicates appeared at most **twice** and return the new length. |
| 10 | + |
| 11 | +Do not allocate extra space for another array, you must do this by **modifying the input array in-place** with O(1) extra memory. |
| 12 | + |
| 13 | +**Example 1:** |
| 14 | + |
| 15 | +``` |
| 16 | +Given nums = [1,1,1,2,2,3], |
| 17 | +
|
| 18 | +Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. |
| 19 | +
|
| 20 | +It doesn't matter what you leave beyond the returned length. |
| 21 | +``` |
| 22 | + |
| 23 | +**Example 2:** |
| 24 | + |
| 25 | +``` |
| 26 | +Given nums = [0,0,1,1,1,1,2,3,3], |
| 27 | +
|
| 28 | +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. |
| 29 | +
|
| 30 | +It doesn't matter what values are set beyond the returned length. |
| 31 | +``` |
| 32 | + |
| 33 | +**Clarification:** |
| 34 | + |
| 35 | +Confused why the returned value is an integer but your answer is an array? |
| 36 | + |
| 37 | +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. |
| 38 | + |
| 39 | +Internally you can think of this: |
| 40 | + |
| 41 | +``` |
| 42 | +// nums is passed in by reference. (i.e., without making a copy) |
| 43 | +int len = removeDuplicates(nums); |
| 44 | +
|
| 45 | +// any modification to nums in your function would be known by the caller. |
| 46 | +// using the length returned by your function, it prints the first len elements. |
| 47 | +for (int i = 0; i < len; i++) { |
| 48 | + print(nums[i]); |
| 49 | +} |
| 50 | +``` |
| 51 | + |
| 52 | +## Solution |
| 53 | + |
| 54 | +```javascript |
| 55 | +/** |
| 56 | + * @param {number[]} nums |
| 57 | + * @return {number} |
| 58 | + */ |
| 59 | +var removeDuplicates = function(nums) { |
| 60 | + var len = nums.length; |
| 61 | + var index = 0; |
| 62 | + var last = NaN; |
| 63 | + var times = 0; |
| 64 | + for (var i = 0; i < len; i++) { |
| 65 | + if (nums[i] === last) { |
| 66 | + if (times < 2) times++; |
| 67 | + else continue; |
| 68 | + } else { |
| 69 | + times = 1; |
| 70 | + } |
| 71 | + last = nums[i]; |
| 72 | + nums[index] = nums[i]; |
| 73 | + index++; |
| 74 | + } |
| 75 | + return index; |
| 76 | +}; |
| 77 | +``` |
| 78 | + |
| 79 | +**Explain:** |
| 80 | + |
| 81 | +nope. |
| 82 | + |
| 83 | +**Complexity:** |
| 84 | + |
| 85 | +* Time complexity : O(n). |
| 86 | +* Space complexity : O(1). |
0 commit comments