Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.數組
Do not allocate extra space for another array, you must do this in place with constant memory.app
For example, Given input array nums = [1,1,2], this
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.spa
時間 O(N) 空間 O(1)指針
咱們能夠將不重複的序列存到數列前面,由於不重複序列的長度必定小於等於總序列,因此不用擔憂覆蓋的問題。具體來講,用兩個指針,快指針指向當前數組遍歷到的位置,慢指針指向不重複序列下一個存放的位置,這樣咱們一旦遍歷到一個不重複的元素,就把它複製到不重複序列的末尾。判斷重複的方法是記錄上一個遍歷到的數字,看是否同樣。code
public class Solution { public int removeDuplicates(int[] nums) { if(nums.length == 0) return 0; int dup = nums[0]; int end = 1; for(int i = 1; i < nums.length; i++){ if(nums[i]!=dup){ nums[end] = nums[i]; dup = nums[i]; end++; } } return end; } }
Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?排序
For example, Given sorted array nums = [1,1,1,2,2,3],element
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.rem
時間 O(N) 空間 O(1)input
思路和上題同樣,區別在於記錄前兩個遍歷到的數字來幫助咱們判斷是否出現了第三遍。若是當前數字和前一個數字的前一個同樣的話,說明出現了第三次。
public class Solution { public int removeDuplicates(int[] nums) { if(nums.length <= 2) return nums.length; int dup1 = nums[0]; int dup2 = nums[1]; int end = 2; for(int i = 2; i < nums.length; i++){ if(nums[i]!=dup1){ nums[end] = nums[i]; dup1 = dup2; dup2 = nums[i]; end++; } } return end; } }
Q:若是數組沒有排序的話如何解?A:能夠先將其排序再用一樣方法求解,然而時間複雜度將達到O(NlogN),若是咱們改用哈希表或集合來記錄數字出現次數,能夠用O(N)空間獲得O(N)的時間。