Leetcode-探索 | 從排序數組中刪除重復項
阿新 • • 發佈:2018-06-20
idea o-c tel != date int -c pan 寫代碼
給定一個排序數組,你需要在原地刪除重復出現的元素,使得每個元素只出現一次,返回移除後數組的新長度。
不要使用額外的數組空間,你必須在原地修改輸入數組並在使用 O(1) 額外空間的條件下完成。
示例 1:
給定數組 nums = [1,1,2], 函數應該返回新的長度 2, 並且原數組 nums 的前兩個元素被修改為1
,2
。 你不需要考慮數組中超出新長度後面的元素。
示例 2:
給定 nums = [0,0,1,1,1,2,2,3,3,4], 函數應該返回新的長度 5, 並且原數組 nums 的前五個元素被修改為0
,1
,2
,3
,4
。 你不需要考慮數組中超出新長度後面的元素。
——————————————————————————————————————————————
這題充分暴露自己寫代碼的時候腦子一團漿糊,動手之前首先要把idea理清楚,用模擬或者圖表說服自己,然後嘗試編碼!
附AC代碼:
1 class Solution(object): 2 def removeDuplicates(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 if len(nums) == 0: 8 return0 9 10 # set i and j who denotes the pos-to-update and the pos-to-compare seperately 11 # nums[i] will always keep in sync with the nums[j] when meeting duplicate numbers 12 list_len = len(nums) 13 14 i = 0 15 j = 0 16 solo_nums = 0 17 18for j in range(0, list_len): 19 if nums[i] != nums[j]: 20 i += 1 21 nums[i] = nums[j] 22 else: 23 solo_nums += 1 24 25 return list_len - solo_nums + 1
即使是智障的題目寫不出來也不要覺得“自己一定能搞定,搞不定就著急”!水題裏面也有自己薄弱的地方,一些小的邏輯必須練習到熟練才可能看起來不費力。
Leetcode-探索 | 從排序數組中刪除重復項