您的位置:首页 > 其它

【LeetCode】马三来刷题之Remove Duplicates from Sorted Array

2016-09-16 18:12 357 查看
恢复刷题第二天,题目链接: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;
}
每天一道题,保持新鲜感,就这样~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: