一个排序数组,移除重复的项,返回新的长度。
不可以使用额外的数组空间,空间复杂度为O(1)。
解析:
- 不可以声明新的空间,就得在原有数组上修改。
- 很容易想到把数组当前项和下一项比较,相等的话就把后面那项删掉
- 下面第二段运行速度会比较快,是比较两项如果不相等,直接将下一项储存
(The following English translation may not be right -.-)
analyze:
- Compare the current item of array with the next item, and delete the next item if they are equal ( the first piece of code below )
- Stored then next item if they are not equal ( the second piece of code below, it run faster then the first )
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
var i = 0
var len = nums.length
while(i < len) {
if(nums[i] == nums[i+1]) {
nums.splice(i+1, 1)
len--
}else {
i++
}
}
return len
};
var removeDuplicates = function(nums) {
let uniqueI = 0;
for (var i = 0; i < nums.length; i++) {
if (nums[uniqueI] != nums[i]) {
uniqueI++;
nums[uniqueI] = nums[i];
}
}
return uniqueI + 1;
};
``