这是我参与2022首次更文挑战的第2天,活动详情查看:2022首次更文挑战
leetcode地址: leetcode-cn.com/problems/re…
思路: 双指针, 左指针移动到比对位置, 右指针移动到下一个不同数字处替换左指针的下一位, 时间复杂度O(n), 空间复杂度O(1)
class Solution {
public int removeDuplicates(int[] nums) {
int m = 0, n = 0;
// 左指针移动到被替换位置, 右指针移动到下一个不同数字处
while (n < nums.length) {
if (nums[m] != nums[n]) {
// 左指针移动一位后替换
nums[++ m] = nums[n];
}
n ++;
}
return m + 1;
}
}