题目
leetcode26. 删除排序数组中的重复项
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
示例 1:
给定数组 nums = [1,1,2],
函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。
你不需要考虑数组中超出新长度后面的元素。
示例 2:
给定 nums = [0,0,1,1,1,2,2,3,3,4],
函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。
你不需要考虑数组中超出新长度后面的元素。
代码
#include <vector>
using namespace std;
class Solution {
public:
// C++
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) {
return 0;
}
auto it = nums.begin();
int val = *it;
++it;
while(it != nums.end()){
if (*it == val) {
// erase返回值指向删除元素的下一位置
it = nums.erase(it);
}else{
val = *it;
++it;
}
}
return nums.size();
}
// C
// 思路:快慢指针
int removeDuplicates(int* nums, int numsSize) {
if (0 == numsSize) {
return 0;
}
int i = 0;
for(int j = 1; j < numsSize; ++j){
if (nums[j] != nums[i]){
++i;
nums[i] = nums[j];
}
}
return i + 1;
}
};
测试
#include <iostream>
void print(const vector<int>& nums) {
cout << "nums : ";
for(auto& i : nums) {
cout << i << " ";
}
cout << std::endl;
}
int main() {
std::vector<int> vc = {
2, 2, 3, 4, 5, 5, 6, 7};
print(vc);
Solution s;
s.removeDuplicates(vc);
print(vc);
std::cin.get();
return 0;
}
- 结果
nums : 2 2 3 4 5 5 6 7
nums : 2 3 4 5 6 7