您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Remove Duplicates from Sorted Array II

2015-10-18 17:03 246 查看

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/

删除数组中重复出现三次或三次以上的数。

两个变量记录上次和上上的值,比较一下,如果出现大于等于三次了,记下下标。

删除的时候要从后往前,这样不会打乱下标的顺序。

/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
var aRemove = [], i, previous, previous2;
for(i = 0; i < nums.length; i++){
if(nums[i] !== previous){
//first time
}else if(nums[i] === previous && nums[i] !== previous2){
//duplicate two times
}else{
//duplicate more than two times
aRemove.push(i);
}
previous2 = previous;
previous = nums[i];
}
for(i = aRemove.length - 1; i >= 0; i--){
nums.splice(aRemove[i], 1);
}
return nums.length;
};


另一种更简洁的做法,开一个变量index,每次把正确的结果放到下标为index的位置上,index++,遍历完之后index就是目标数组的长度。

/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
var index = 0, i, previous, previous2;
for(i = 0; i < nums.length; i++){
if(nums[i] !== previous){
nums[index++] = nums[i];
}else if(nums[i] === previous && nums[i] !== previous2){
nums[index++] = nums[i];
}
previous2 = previous;
previous = nums[i];
}
return index;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: