删除排序数组中的重复项

解法一

双指针
使用双指针left、right,找到第一个nums[left] !== nums[right]的元素,将nums[right]填到nums[left]上,然后left++、right++。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function (nums) {
// 双指针
let left = (right = 0);
while (right < nums.length) {
// 找到第一个不等于left的元素
while (nums[right] === nums[left]) {
right++;
}
if (right < nums.length && nums[left] !== nums[right]) {
if (right > left + 1) {
nums[left + 1] = nums[right];
}
left++;
}
right++;
}
return left + 1;
};
// removeDuplicates([1, 1, 2]);
// removeDuplicates([1, 1]);
// removeDuplicates([0, 0, 1, 1, 1, 2, 2, 3, 3, 4]);

解法二

三次翻转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function (nums, k) {
const length = nums.length;
const count = k % length;
if (count === 0) return;
// 翻转
function reverse(left, right) {
while (left < right) {
[nums[left], nums[right]] = [nums[right], nums[left]];
left++;
right--;
}
}
reverse(0, length - 1);
reverse(0, count - 1);
reverse(count, length - 1);
};
// rotate([1, 2, 3, 4, 5, 6, 7], 3);


本站由 ao 使用 Stellar 1.29.1 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。