Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.javascript
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.java
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:app
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:this
Confused why the returned value is an integer but your answer is an array?spa
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.code
Internally you can think of this:ip
// 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]); }
給定一個有序數組,要求將數組中具備重複值的元素依次排在數組前部,且同一個值對應的元素最多有兩個,返回構成的新數組的長度。element
在 26. Remove Duplicates from Sorted Array 的基礎上加上了條件:重複元素最多保留兩個。方法也比較簡單:設一個變量count記錄新數組最後一個元素的重複次數。遍歷原數組,每次都將當前元素和新數組的最後一個元素進行比較,若是不一樣則直接移入新數組,並將count重置爲1;若是相同,判斷count的值,只有當重複次數count=1時纔將當前元素移入新數組,並使count加1。leetcode
class Solution { public int removeDuplicates(int[] nums) { int p = 0; int count = 1; for (int i = 1; i < nums.length; i++) { if (nums[i] == nums[p] && count == 1) { nums[++p] = nums[i]; count++; } else if (nums[i] != nums[p]) { nums[++p] = nums[i]; count = 1; } } return p + 1; } }
/** * @param {number[]} nums * @return {number} */ var removeDuplicates = function (nums) { let p = 0, q = 0 let cur = nums[0], cnt = 0 for (let num of nums) { if (num === cur) { cnt++ } else { cur = num cnt = 1 } if (cnt <= 2) { nums[p++] = nums[q] } q++ } return p }