题目链接https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/题目:
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.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of nums.
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
思路:
注意不能使用非常数的额外空间,所以不能定义数组!算法只有一个变量:记录目前重复的元素个数moveforward:每遇到一个和上一个元素相同的元素的时候,这个数量加一,然后将这个元素前置到它之前moveforward的位置上(当然如果和前一个元素不相同的话也会移动到前面,只不过moveforward不会增加罢了)。由于moveforward恒小于i,因此不会对之前的数据有影响。这个可以很容易理解。
代码:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int moveforward;
int same=0;
int len=nums.size();
for(int i=0;i<len;i++){
if(i==0) moveforward=0;
else if(nums[i]==nums[i-1]) moveforward++;
nums[i-moveforward]=nums[i];
}
return len-moveforward;
}
};