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