Type:easy
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
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:
Givennums=[1,1,2],Your function should return length =2, with the first two elements ofnumsbeing1and2respectively.It doesn't matter what you leave beyond the returned length.
Example 2:
Givennums=[0,0,1,1,1,2,2,3,3,4],Your function should return length =5, with the first five elements ofnumsbeing modified to0,1,2,3, and4respectively.It doesn't matter what values are set beyond the returned length.
本题给定一个有序数组,删去其中重复的数值,返回无重复数值的新数组。注意本题要求不能开其他的新数组,而是返回这个原本的数组。
遍历该数组,设 count 值为重复的数值数量,则当遍历到第 i 个数字时,若 i+1 与 i 不相同,将 nums[i+1] 的值赋给nums[i+1-count] 即可。
这道题的算法还是蛮有意思的,应该记一下。可以这么记,若重复的数值数量为 count,则最后返回的数组大小应为原nums.size() - count ,最后一位的下标是 nums.size() - count -1。也就是说当 i+1 若是最后一个数,nums.size() 为 i+2 ,那么这个 nums[i+1] 的值应该在第 i+1-count 处,因此返回的数组位置为 nums[i+1-count]。
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int count = 0;
int n = nums.size();
for(int i=0; i<n-1; i++){
if(nums[i+1] == nums[i]){
count++;
}
else nums[i+1-count] = nums[i+1];
}
return n-count;
}
};