Given a sorted array, remove the duplicates in place such that each element appear onlyonceand return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,Given input arraynums=[1,1,2],
Your function should return length =2, with the first two elements ofnumsbeing1and2respectively. It doesn't matter what you leave beyond the new length.
因為這是一個sorted array。所以如果幾個數字的值相等,那么他們一定是排列在一起的。所以我們只要檢查這個數和他相鄰的數是否相等就可以了。
但注意,因為我們要output改變后的list。所以還需要一個int來輔助我們調整排列整個list。當一個數和他周圍的數不相等的話,他的位置不會有改變。但是當兩個相鄰的數相等的話,第二個數后面的一個數的位置就需要往前挪動一個了。當然如果連續3個數相等,就是往前移動2個位置了。
注意count的初始值要為1,因為除了specail case外,nums的長度至少都為1。
注意這點。其他的都好辦了。代碼如下。~
public class Solution { public int removeDuplicates(int[] nums) { if (nums == null || nums.length == 0) return 0; int count = 1; for (int i = 1; i < nums.length; i++){ if (nums[i]!=nums[i-1]){ nums[count] = nums[i]; index++; } } return count; }}
新聞熱點
疑難解答