LeetCode-26
Links:https://leetcode.com/problems/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.
题意:删除指定元素,不使用额外空间.
思路1:STL模板库,unique()函数,distance()函数.
1 2 3 4 5 6 7 |
class Solution { public: int removeDuplicates(vector<int>& nums) { nums = vector<int>(nums.begin(),unique(nums.begin(),nums.end())); return nums.size(); } }; |
1 2 3 4 5 6 |
class Solution { public: int removeDuplicates(vector<int>& nums) { return distance(nums.begin(),unique(nums.begin(),nums.end())); } }; |
思路2:因为已经排序好了,所以一次遍历替换即可.比前面那个稍快一些…速度都一样。
因为要求不能使用额外空间.所以第二种方法符合题意.但是还是达不到最快的那种…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Solution { public: int removeDuplicates(vector<int>& nums) { if(nums.size()<=1)return nums.size(); vector<int>temp; temp.push_back(nums[0]); for(int i=1;i<nums.size();i++) { if(nums[i] != temp[temp.size()-1]) temp.push_back(nums[i]); } nums = temp; return nums.size(); } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Solution { public: int removeDuplicates(vector<int>& nums) { if(nums.size()<=1) return nums.size(); int index = 1; for(int i = 1;i < nums.size(); i++){ if(nums[i] != nums[i-1]){ nums[index++] = nums[i]; } } return index; } }; |
【LeetCode】26. Remove Duplicates from Sorted Array