Leetcode-Array-26.删除有序数组中的重复项

https://leetcode.cn/problems/remove-duplicates-from-sorted-array/?envType=study-plan-v2&envId=top-interview-150

思路

重点:非严格递增、原地删除、相对顺序一致

使用双指针,left 指针表示当前去重结果,right 指针找到下一个替换位置。因为要保持相对顺序,我们从左向右查找

伪代码:

1
2
3
4
5
6
7
8
left=1 right=1
while right<len:
if nums[left-1]==nums[right]:
right++
else:
swap(nums[left],nums[right])
left++;right++;
return left

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int removeDuplicates(int[] nums) {
int left =1,right=1;
while(right<nums.length){
if(nums[left-1]==nums[right]){
right++;
}else{
// 这里没必要交换
// int temp=nums[left];
nums[left]=nums[right];
// nums[right]=temp;
right++;
left++;
}
}
return left;
}
}