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.
Solution1:
At first glance this problem thought is not done and do heavy. Turned back to see the next remove element, found to be two different problems. But the idea is almost identical. Save an index from the last one before checking, if the difference is to save the new number, if the same is skipped. The last index is the length. A little tricky is starting from two, but it's easy to know.
Public classSolution { Public intRemoveDuplicates (int[] nums) { if(nums.length==0) { return0; } if(nums.length==1) { return1; } intIndex=1; for(inti=1;i<nums.length;i++) { if(nums[i]==nums[i-1]) { Continue; } Else{Nums[index++]=Nums[i]; } } returnindex; }}
. Remove duplicates from Sorted Array