Title Description
Given a sorted array, you need to Delete the repeating element in place so that each element appears up to two times, returning the new length of the array after it is removed.
Instead of using extra array space, you must modify the input array in place and complete it with O (1) Extra space.
Example 1:
Nums [1,1,1,2,2,3] 5
. 1, 1, 2, 2,
You do not need to consider elements that are beyond the new length in the array.
Example 2:
Nums [0,0,1,1,1,1,2,3,3] 0
, and the first five elements of the original array are modified to 0 1 1 2 3 3. 7
you do not need to consider elements that are beyond the new length in the array.
Description
Why is the return value an integer, but the answer to the output is an array?
Note that the input array is passed in a "reference" manner, which means that modifying the input array in the function is visible to the caller.
You can imagine the internal operation as follows:
The nums is passed in a "reference" manner. That is, do not make any copy of the argument int len = removeduplicates (nums);//Modifying an input array in a function is visible to the caller. Depending on the length returned by your function, it prints all the elements within that length range in the array. for (int i = 0; i < len; i++) {print (nums[i]);}
Thinking of solving problems
The double pointer method maintains the left and right pointers, where the right pointer points to the second number after the left pointer or to a different number immediately after. If you find a duplicate number greater than two, delete the number pointed to by the right pointer, knowing that the right pointer is different from the left pointer. Note Update the array length minus one when the number is deleted.
Code
1 classSolution {2 Public:3 intRemoveDuplicates (vector<int>&nums) {4 intSize =nums.size ();5 intleft =0, right =1;6 while(Right <size) {7 while(Nums[left] = = Nums[right] && Right-left <2)8right++;9 while(Nums[left] = = Nums[right] && Right <size) {Tenvector<int>::iterator iter = Nums.begin () +Right ; One Nums.erase (ITER); Asize--; - } -left =Right ; theright++; - } - returnsize; - } +};
Leetcode 80. Delete duplicates in sorted array II (remove duplicates from Sorted Array II)