【leetcode c++】26 Remove Duplicates from Sorted Array

来源:互联网 发布:windows查看tomcat日志 编辑:程序博客网 时间:2024/05/10 14:01

Given a sorted array, remove the duplicatesin place such that each element appear only once and return the new length.

 

Do not allocate extra space for anotherarray, 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'tmatter what you leave beyond the new length.

 

给你一个有序数组,把重复的元素都‘删’到只剩下一个为止。返回新数组的长度。

不允许使用额外的数组。也不允许扩充数组。

比如:

输入是nums =[1,1,2],

你的函数则需要返回length= 2,同时数组的前两位是12,我并不在意在此之后的元素是什么。

 

也就是,所谓的‘删除’,就是把它丢到数组尾部而已。

当然,真的要做删除操作也可以,但是请注意,输入是个数组vector<int>& nums。用erase真的好吗?

 

那现在就考虑怎么换。题目的要求要我们找相同元素并且移到尾。如果输入是链表的话,这个做法是完美的。但是输入是个数组,如果真要这么实现,我们必须要把后面的元素全部前移才能插尾,这效率跟直接erase差不多了吧估计。驳回。

那么只能把扫描跟交换同时进行了。我们反其道而行,找不同元素并且移到头。

 

数组长度小于2的另作判断。

取两个指针指向数组第一第二个元素。如果此时这两个元素不相等,那么两个指针同时后移。这里给的图示是第一第二个元素相等,那么第二个指针后移,一直移到它指向的元素跟第一个指针指向的元素不相等为止。



这时候,这两个指针之间的元素必然是重复元素。所以后移第一个指针。


交换两个指针指向的元素。


这时候,从数组头开始,到第一个指针指向的元素都是不重复元素。

我们让第二个指针后移。


两个指针之间都是重复元素。

这时候,继续后移第二个指针。直到它指向的元素跟第一个指针指向的元素不相等为止。


找到不同之后,这时候,这两个指针之间的元素必然是重复元素。所以后移第一个指针。



交换两个指针指向的元素。


这时候,从数组头开始,到第一个指针指向的元素都是不重复元素……


这时候两个指针之间都是垃圾元素……

……

……

一直扫描下去。当第二个指针扫描完数组,那么第一个指针之前的元素都是不重复元素了。

LeetcodeAcceptedSolutions Runtime Distribution15-06-07

 

源码:(VS2013)如果需要提交leetcode只需要把twoSun函数中的代码复制过去即可。

#include <iostream>#include <vector>using namespace std;void showVector(const vector<int>& nums);int removeDuplicates(vector<int>& nums);int main(){vector<int> nums;nums.push_back(2);nums.push_back(1);nums.push_back(3);nums.push_back(0);nums.push_back(1);nums.push_back(1);nums.push_back(0);nums.push_back(3);nums.push_back(3);nums.push_back(1);nums.push_back(3);cout << removeDuplicates(nums);return 1;}int removeDuplicates(vector<int>& nums){/////////////////////////////////////////////////leetcode26/////////////////////////////////////////////////.swap();int len = nums.size();if (0 == len) return 0;if (1 == len) return 1;vector<int>::iterator iter1 = nums.begin();vector<int>::iterator iter2 = iter1;vector<int>::iterator iterEnd = nums.end();iter2++;while (iterEnd != iter2){if (*iter1 == *iter2){iter2++;len--;}else{iter1++;swap(*iter1, *iter2);iter2++;}}return len;}void showVector(const vector<int>& nums){for each (int i in nums){cout << i << " ";}cout << endl;}


0 0
原创粉丝点击