Remove Duplicates from Sorted Array 题解
题目来源:https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
Description
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 by modifying the input array in-place with O(1) extra memory.
Example
Given 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.
Solution
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) return 0;
int t = nums[0];
auto it = nums.begin();
while (it != nums.end()) {
for (it = nums.begin(); it != nums.end(); ++it) {
if (it > nums.begin() && (*it) == t) {
nums.erase(it);
break;
}
t = *it;
}
}
return nums.size();
}
};
解题描述
这道题题意是对给出的一个排好序的数据,删掉其中重复的元素,并且要求空间复杂度为O(1)。上面给出的是我一开始用的比较暴力的办法,使用迭代器来删除vector中元素的办法。
下面给出的是评论区的方法,只需要多使用一个id
作为非重复元素标志位即可:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty())
return 0;
int size = nums.size();
int id = 1;
for (int i = 1; i < size; i++) {
if (nums[i] != nums[i - 1])
nums[id++] = nums[i];
}
return id;
}
};