Remove Duplicates from Sorted Array II
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array 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
. It doesn‘t matter what you leave beyond the new length.
https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
删除数组中重复出现三次或三次以上的数。
两个变量记录上次和上上的值,比较一下,如果出现大于等于三次了,记下下标。
删除的时候要从后往前,这样不会打乱下标的顺序。
1 /** 2 * @param {number[]} nums 3 * @return {number} 4 */ 5 var removeDuplicates = function(nums) { 6 var aRemove = [], i, previous, previous2; 7 for(i = 0; i < nums.length; i++){ 8 if(nums[i] !== previous){ 9 //first time 10 }else if(nums[i] === previous && nums[i] !== previous2){ 11 //duplicate two times 12 }else{ 13 //duplicate more than two times 14 aRemove.push(i); 15 } 16 previous2 = previous; 17 previous = nums[i]; 18 } 19 for(i = aRemove.length - 1; i >= 0; i--){ 20 nums.splice(aRemove[i], 1); 21 } 22 return nums.length; 23 };
另一种更简洁的做法,开一个变量index,每次把正确的结果放到下标为index的位置上,index++,遍历完之后index就是目标数组的长度。
1 /** 2 * @param {number[]} nums 3 * @return {number} 4 */ 5 var removeDuplicates = function(nums) { 6 var index = 0, i, previous, previous2; 7 for(i = 0; i < nums.length; i++){ 8 if(nums[i] !== previous){ 9 nums[index++] = nums[i]; 10 }else if(nums[i] === previous && nums[i] !== previous2){ 11 nums[index++] = nums[i]; 12 } 13 previous2 = previous; 14 previous = nums[i]; 15 } 16 return index; 17 };
时间: 2024-10-26 22:35:43