Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
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.
解题思路:
很简单,重新生成数组即可。
代码如下:
#include<algorithm>
class Solution{
public:
int removeDuplicates(vector<int>& nums) {
vector<int> res;
if (nums.size() == 0) return 0;
int l = 1;
int former = nums[0];
res.push_back(nums[0]);
int preIdx = 0
for (int i = 1; i < nums.size(); ++i){
if (former != nums[i]){
++l;
former = nums[i];
}
}
nums = res;
return l;
}
};结果如下:
本文介绍了一种从已排序数组中去除重复元素的方法,确保每个元素只出现一次,并返回处理后的数组长度。示例中,输入数组 [1,1,2] 经过处理后,前两个元素为 1 和 2,新长度为 2。
1041

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



