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.
Have you met this question in a real interview?
Yes
Example
Tags Expand
Given input array
A = [1,1,2]
,
Your function should return
length = 2
, and A is now [1,2]
.Use vector.erase() function:
Just check repetition one by one. Well, just write it for fun.
Time: O(n2)
Space: O(n)
class Solution { public: /** * @param A: a list of integers * @return : return an integer */ int removeDuplicates(vector<int> &nums) { // write your code here //check element after current element for(int i = 0; i < nums.size(); i++){ if(i >= nums.size() - 1) break; if(nums[i] == nums[i+1]) { nums.erase(nums.begin() + i); i--; } } return nums.size(); //check element before current element for(int i = 1; i < nums.size(); i++){ if(i >= nums.size()) break; if(nums[i] == nums[i - 1]) { nums.erase(nums.begin() + i); i--; } } return nums.size(); } };
Two pointers:
One pointer iterates each element from the array. The other pointer is used to store element which is not duplicated with others.
Time: O(n)
Space: O(n)
class Solution { public: /** * @param A: a list of integers * @return : return an integer */ int removeDuplicates(vector<int> &nums) { //compare to rear element if(nums.size() == 0) return 0; int j = 1; for(int i = 1; i < nums.size(); i++){ if(nums[i] != nums[i - 1]) nums[j++] = nums[i]; } return j; //compare to front element if(nums.size() == 0) return 0; int j = 0; for(int i = 0; i < nums.size() - 1; i++){ if(nums[i] != nums[i + 1]) nums[j++] = nums[i]; } nums[j] = nums.back(); return j + 1; } };
Second SHUA:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Solution { public: /** * @param A: a list of integers * @return : return an integer */ int removeDuplicates(vector<int> &nums) { // write your code here if(nums.size() == 0) return 0; int cur = 1; for(int i = 1; i < nums.size(); i++){ if(nums[i] != nums[i - 1]){ nums[cur] = nums[i]; cur++; } } return cur; } }; |
没有评论:
发表评论