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.
Public classSolution {//There is a requirement: you need to deal with it in situ, that is, you cannot occupy extra space. So consider declaring a pointer, the value in front of the pointer is non-repeating//then iterate through the array, each value is compared with its previous value, if the same, the forward index, if different, put this value in front of the array//here is a solution, the disadvantage of the second solution is that when a non-repeating array, nums[start++]=nums[index++] throw will run//the initial value of start should be noted. Public intRemoveDuplicates (int[] nums) { if(nums.length==0)return0; intStart=1; intIndex=1; while(index<nums.length) { if(nums[index]==nums[index-1]) {index++; }Else{Nums[start++]=nums[index++]; } } returnstart; } }
[Leedcode 26] Remove Duplicates from Sorted Array