/* 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. */
解决思路:
使用迭代器遍历vector,非重复时 length++,删除重复元素。
class Solution { public: int removeDuplicates(vector<int>& nums) { if (nums.size() == 0) return 0; int ans = 1; for (auto itr = nums.begin()+1; itr != nums.end();) { if (*itr == *(itr-1)) itr = nums.erase(itr); else { ans++; itr++; } } return ans; } };
discuss:
题意不考虑vector中length之后的值,可以不做删除,选择覆盖前length 个元素 。稍快于解法1
int removeDuplicates(vector<int>& nums) { int i = !nums.empty(); for (int n : nums) if (n > nums[i-1]) nums[i++] = n; return i; }
时间: 2024-10-25 13:42:36