No.26 Remove Duplicates from Sorted Array
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.
Tags: Array Two Pointers
移除有序数组中的重复数字
要求:原地移除,不能使用额外空间;返回新数组的长度
典型的两指针
1 #include "stdafx.h" 2 #include <map> 3 #include <vector> 4 #include <iostream> 5 using namespace std; 6 7 class Solution 8 { 9 public: 10 int removeDuplicates(vector<int> &nums) 11 {//移除有序数组中的重复数字 12 //要求:原地移除,不能使用额外空间;返回新数组的长度 13 int size = nums.size(); 14 if(size <= 1) 15 return size; 16 17 int index=0;//无重复数字的最后索引 18 for(int i=1; i<size; i++) 19 { 20 if(nums[i] != nums[index])//重复数字,无视 21 nums[++index] = nums[i]; 22 } 23 nums.erase(nums.begin()+index+1,nums.end()); 24 return index+1; 25 } 26 }; 27 28 int main() 29 { 30 Solution sol; 31 int data[] = {1,1,1,1}; 32 vector<int> test(data,data+sizeof(data)/sizeof(int)); 33 for(const auto &i : test) 34 cout << i << " "; 35 cout << endl; 36 cout<< boolalpha << sol.removeDuplicates(test)<<endl; 37 for(const auto &i : test) 38 cout << i << " "; 39 cout << endl; 40 }