恢复刷题第二天,题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array/
26. Remove Duplicates from Sorted Array
- Total Accepted: 157568
- Total Submissions: 454924
- Difficulty: Easy
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.
Subscribe to see which companies asked this question
题目很简单,给定一个排序好的数组,把相同的元素从原来的位置移除,并且返回一个不包含重复元素的长度即可。
同样是用了两种方法过的这道题,分别是unique和数组逐个比较的办法。
方法一:使用unique()函数:
int removeDuplicates(vector<int>& nums) {
//unique()函数将重复的元素放到vector的尾部 然后返回指向第一个重复元素的迭代器
//再用erase函数擦除从这个元素到最后元素的所有的元素
nums.erase(unique(nums.begin(),nums.end()),nums.end());
return nums.size();
}
方法二:数组元素逐个比较:
int removeDuplicates(vector<int>& nums)
{
if (nums.empty()) return 0;
int index = 0;
for (int i = 1; i < nums.size(); i++)
{
if (nums[index] != nums[i])
nums[++index] = nums[i];
}
return index + 1;
}
每天一道题,保持新鲜感,就这样~
本文介绍了LeetCode第26题——有序数组去重问题,难度为Easy。要求在原地修改数组,使得每个元素仅出现一次,并返回新长度。文章提供了两种解题方法,包括使用unique()函数和数组逐个比较。

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



