Remove Duplicates from Sorted Array
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
多个方法,其中带erase的耗时时间比较长
class Solution { public: /* * 遍历vector如果第一个数字和前面相邻相等,就去掉第该数字 * */ int _removeDuplicates(vector<int>& nums) { int len = 0; int value = INT_MIN; int i = 0; for (i=0; i< nums.size(); i++) { if (nums[i] != value) { value = nums[i]; len++; } else { nums.erase(nums.begin() + i); i--; } } return len; } int __removeDuplicates(vector<int>& nums) { int len = 0; int value = INT_MAX; nums.push_back(INT_MIN); vector<int>::iterator iter = nums.begin(); while ((*iter) != INT_MIN) { if ((*iter) != value) { value = (*iter); len++; iter++; } else { nums.erase(iter); } } return len; } //新弄一个vector,将不重复的放入该vector中 int removeDuplicates(vector<int>& nums) { vector<int> res; int value = INT_MAX; nums.push_back(INT_MIN); vector<int>::iterator iter = nums.begin(); while ((*iter) != INT_MIN) { if ((*iter) != value) { value = (*iter); res.push_back(value); } iter++; } nums = res; return res.size(); } };
posted on 2016-01-10 22:42 walkwalkwalk 阅读(180) 评论(0) 编辑 收藏 举报