Leetcode 26. Remove Duplicates from Sorted Array
26. Remove Duplicates from Sorted Array
- Total Accepted: 142614
- Total Submissions: 418062
- 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.
思路:重复的元素只保留1个,最后返回没有重复元素的vector.size()。
代码:
写法一:直接删除重复元素。
1 class Solution {
2 public:
3 int removeDuplicates(vector<int>& nums) {
4 int i=0,j;
5 while(i<nums.size()){
6 int temp=nums[i];
7 while(i<nums.size()&&nums[i]==temp){
8 nums.erase(nums.begin()+i);
9 }
10 nums.insert(nums.begin()+i,temp);
11 i++;
12 }
13 return nums.size();
14 }
15 };
写法二:用id指针,只保留未重复的数。
1 class Solution { 2 public: 3 int removeDuplicates(vector<int>& nums) { 4 if(nums.size()==0){ 5 return 0; 6 } 7 int id=1,n=nums.size(); 8 for(int i = 1; i < n; ++i) 9 if(nums[i] != nums[i-1]) nums[id++] = nums[i]; 10 return id; 11 } 12 };
写法三:
1 class Solution { 2 public: 3 int removeDuplicates(vector<int>& nums) { 4 int count=0,n=nums.size(); 5 for(int i=1; i<n; i++){ 6 if(nums[i] == nums[i-1]) count++;//count记录重复的元素个数 7 else nums[i-count] = nums[i]; 8 } 9 return n-count; 10 } 11 };
一个比一个巧妙。