Title:
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.
Tips:
This problem requires no additional memory space, so we need to operate on the original array, for such problems, usually can be "a fast and slow double pointer" method to solve, the following code is very easy to understand.
Code:
classSolution { Public: intRemoveDuplicates (vector<int>&nums) { if(Nums.size () <=1)returnnums.size (); inti =0; for(intj =1; J < Nums.size (); ++j)if(Nums[i] < nums[j]) nums[++i] =Nums[j]; return++i; }};
"Leetcode" 26. Remove Duplicates from Sorted Array