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:
Given nums = [1,1,2],Your function should return length =2
, with the first two elements ofnums
being1
and2
respectively.It doesn't matter what you leave beyond the returned l
分析:
该题要求返回删除排序数组中重复项后数组的长度,可以从第二位开始依次与前一位数比较,若不同,则返回的长度len+1,直至遍历完整个数组。
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size() == 0)
return 0;
int len = 1;
for(int index = 1; index < nums.size(); index++){
if(nums[index] != nums[index-1]){
if(nums[index] != nums[len])
nums[len] = nums[index];
len++;
}
}
return len;
}
};