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.
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]); }
删除排序数组中的重复项 II。
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度。不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
思路跟版本一差不多,但是需要隔开两个位置。创建一个p指针,指向第一个无效的位置。比如第一个例子,p一开始指向第三个1的位置,因为这个位置上的数字一定是无效的,需要被替换。因为题目要求可以有重复两次的元素所以头两个元素不需要改动。然后每次去跟p - 2上数字比较,看是否重复,没有重复就放入数组同时p++。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public int removeDuplicates(int[] nums) { 3 // corner case 4 if (nums.length <= 2) { 5 return nums.length; 6 } 7 8 // normal case 9 int p = 2; 10 for (int i = 2; i < nums.length; i++) { 11 if (nums[i] != nums[p - 2]) { 12 nums[p] = nums[i]; 13 p++; 14 } 15 } 16 return p; 17 } 18 }
JavaScript实现
1 /** 2 * @param {number[]} nums 3 * @return {number} 4 */ 5 var removeDuplicates = function(nums) { 6 // corner case 7 if (nums.length <= 2) return nums.length; 8 9 // normal case 10 let res = 2; 11 for (let i = 2; i < nums.length; i++) { 12 if (nums[i] !== nums[res - 2]) { 13 nums[res] = nums[i]; 14 res++; 15 } 16 } 17 return res; 18 };