https://leetcode.com/problems/remove-duplicates-from-sorted-array/
Given a sorted array, remove the duplicates in place such, all element appear only once and return the new L Ength.
Do the allocate extra space for another array, and you must does this on place with constant memory.
For example,
Given input array nums = [1,1,2]
,
Your function should return length = 2
, with the first of the elements of nums being and 1
2
Respectivel Y. It doesn ' t matter what are you leave beyond the new length.
Ideas:
is also the pointer idea, the use of the new array arbitrary element must not be larger than the old array of the element corresponding to the index of the principle (also can be seen as a stack), through two pointers to characterize the old and new array.
Iterate through the array, pressing into the new array only when a new element is encountered.
AC Code:
1 classSolution {2 Public:3 intRemoveDuplicates (vector<int>&nums) {4 if(nums.size () = =0)5 return 0;6 intp=0, n=nums.size ();7 for(intI=1; i<n;i++){8 if(nums[i]!=Nums[p]) {9nums[++p]=Nums[i];Ten } One } A returnp+1; - } -};
Leetcode (26): Remove duplicates from Sorted Array