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.
Test instructions
Gives a sorted array, deletes the repeating elements in the array, and returns the new array length. The new array cannot be used, and the spatial complexity used should be constant.
Ideas:
Maintains two pointers, the first one records the length of the currently active element, the other one traverses backwards, and then skips the repeating elements.
Because the arrays are ordered, duplicate elements must be contiguous and no additional records are required. Time complexity is O (n), Spatial complexity O (1).
Public classSolution { Public intRemoveDuplicates (int[] nums) { if(Nums = =NULL|| Nums.length = = 0){ return0; } intindex = 1; for(inti=1;i<nums.length;i++){ if(Nums[i]! = nums[i-1]) {Nums[index]=Nums[i]; Index++; } } returnindex; }}
Leetcode 26. Remove Duplicates from Sorted Array