Given a sorted array, 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 in place with constant memory.
For example,
Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the new length.
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size() ==1)
return 1;
int cnt = 0;
for(int i=0;i<nums.size();){
nums[cnt++] = nums[i];
while(i<nums.size()-1 && nums[i]==nums[i+1]){
i++;
}
i++;
}
return cnt;
}
};
去除数组重复元素
本文介绍了一个C++程序,该程序可以有效地去除已排序数组中的重复元素,并返回处理后的数组长度。此方法不需要额外分配内存空间,完全在原数组中进行操作。
1088

被折叠的 条评论
为什么被折叠?



