Skip to content

Commit 8a12b05

Browse files
committed
26. 删除有序数组中的重复项 (二刷)
1 parent 17f22d5 commit 8a12b05

File tree

1 file changed

+11
-12
lines changed

1 file changed

+11
-12
lines changed

algorithms/remove-duplicates-from-sorted-array.js

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,19 @@
44
* @return {number}
55
*/
66
var removeDuplicates = function (nums) {
7-
// 双指针
8-
if (nums.length === 0) {
9-
return 0;
7+
// 双指针 (快慢指针)
8+
9+
if (nums.length <= 1) {
10+
return nums.length;
1011
}
11-
let slow = 1;
12-
let fast = 1;
13-
14-
while (fast < nums.length) {
15-
if (nums[fast] !== nums[fast - 1]) {
16-
nums[slow] = nums[fast];
17-
slow++;
12+
13+
let slowIndex = 1;
14+
15+
for (let fastIndex = 1; fastIndex < nums.length; fastIndex++) {
16+
if (nums[fastIndex - 1] !== nums[fastIndex]) {
17+
nums[slowIndex++] = nums[fastIndex];
1818
}
19-
fast++;
2019
}
2120

22-
return slow;
21+
return slowIndex;
2322
};

0 commit comments

Comments
 (0)