力扣 - 26. 删除排序数组中的重复项
题目
思路
- 使用快慢指针
- 初始化:将慢指针slow指向数组索引为 0 的位置,然后快指针fast指向索引为 1 的位置
- 例如:0 0 1 1 1 2 2 3 3 4:
- 此时:0 0 1 1 1 2 2 3 3 4,我们比较 slow 和 fast 的大小,0和0相等,那么slow不动,fast后移一位
- 此时:0 0 1 1 1 2 2 3 3 4,0和1不相等,那么我们将slow的下一位赋值为fast的值,然后将slow和fast同时后移一位
- 此时:0 1 1 1 1 2 2 3 3 4,1和1相等,fast移动,slow不动
- 此时:0 1 1 1 1 2 2 3 3 4,1和1相等,fast移动,slow不动
- 此时:0 1 1 1 1 2 2 3 3 4,1和2不相等,slow下一位赋值为fast值,slow和fast后移
- 此时:0 1 2 1 1 2 2 3 3 4,2和2相等,仅fast移动
- 此时:0 1 2 1 1 2 2 3 3 4,2和3不相等,slow下一位赋值为fast值,slow和fast后移
- 此时:0 1 2 3 1 2 2 3 3 4,3和3相等,仅fast移动
- 此时:0 1 2 3 1 2 2 3 3 4,3和4不相等,slow下一位赋值为fast值,slow和fast后移
- 此时:0 1 2 3 4 2 2 3 3 4,然后fast到达数组末端,结束遍历,slow值为4,但是结果要的是数组长度,所以slow要+1
代码
class Solution {
public int removeDuplicates(int[] nums) {
int slow = 0;
for(int fast = 1; fast < nums.length; fast++) {
if (nums[slow] != nums[fast]) {
nums[slow+1] = nums[fast];
slow++;
}
}
return slow + 1;
}
}
复杂度分析
- 时间复杂度:\(O(N)\),其中 N 为数组长度
- 空间复杂度:\(O(1)\)
我走得很慢,但我从不后退!

浙公网安备 33010602011771号