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 and elements Of nums Being 1
and 2
respectively. It doesn ' t matter what are you leave beyond the new length.
translation :
Give you a sequential array, remove the duplicate elements, and do not use extra controls to return the number of occurrences only once
Ideas :
Traverse from the beginning, because the array is in order, if the current element is encountered and the previous element is not the same, then join, otherwise continue to traverse.
It's a very simple question. As for no additional space, directly with the original array position operation can be.
Code :
public static int removeduplicates (int[] nums) { int count = 1;if (nums ==null | | Nums.length = = 0) {return 0;} for (int i = 1;i<nums.length;i++) {if (nums[i]!=nums[i-1]) nums[count++] = nums[i];} return count; }
Leetcode Remove duplicates from Sorted Array