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 }