双指针
数组已有序,重复元素一定相邻。用 left 指向新数组的最后一个位置,right 扫描原数组,遇到不同的值就写入 left + 1。
时间复杂度
空间复杂度
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Solution { public int removeDuplicates(int[] nums) { int left = 0, right = 1, n = nums.length; while (right < n) { if (nums[right] != nums[left]) { left++; nums[left] = nums[right]; } right++; } return left + 1; } }
|