26. 删除有序数组中的重复项 - 力扣(LeetCode)
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements to nums.
Consider the number of unique elements of nums to be k. To get accepted, you need to do the following things:
Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
Return k.
给你一个 升序排列 的数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。元素的 相对顺序 应该保持 一致 。然后返回 nums 中唯一元素的个数。
考虑 nums 的唯一元素的数量为 k ,你需要做以下事情确保你的题解可以被通过:
更改数组 nums ,使 nums 的前 k 个元素包含唯一元素,并按照它们最初在 nums 中出现的顺序排列。nums 的其余元素与 nums 的大小不重要。返回 k 。
//手撕
class Solution {
public int removeDuplicates(int[] nums) {
int length =nums.length;
if(length==0){
return 0;
}
int left=1;
int right=1;
while(right<length){
if(nums[right]!=nums[right-1]){
nums[left]=nums[right];
left++;
}
right++;
}
return left;
}
}
题解:本题在删除元素同时要保持相对位置不变,所以采用快慢指针的方法,在快指针与前一个位置数值不同时则说明移动到了替换位置这时将其替换当前left,需要注意的是在运动过程中快指针容易跳动多个位置,左指针只有在需要变换时才向后移位即移至替换位。