iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 12
0
自我挑戰組

Leetcode新手挑戰30天系列 第 12

#26 Remove Duplicates from Sorted Array - 研究其他解法

前情提要

昨天試寫了一段,測試後的結果和預期完全不同,加上print查也沒找到出問題的地方
https://ithelp.ithome.com.tw/upload/images/20190913/20113393n85xxTE5Dl.png
所以今天決定先來研究下別人的解法

進入正題

下面是我在參考1連結裡找到的解法

def removeDuplicates(self, nums):
    if len(nums) <= 1:
        return len(nums)
    s = 0
    for f in range(1, len(nums)):
        if nums[s] != nums[f]:
            s += 1
            nums[s] = nums[f]
    return s + 1

連結裡有解釋他的想法,是把第一次出現的數字往前移動
例如測試個案輸入[1,1,2],在這邊就會變成[1,2,2],因為輸出只會輸出到第1個位置,會變成[1,2]
像這樣:
https://ithelp.ithome.com.tw/upload/images/20190913/20113393grnn17ocMi.png
測試個案輸入變成[0,0,1,1,1,2,2,3,3,4]的話,就會變成這樣:
https://ithelp.ithome.com.tw/upload/images/20190913/20113393MXfDvs3wVD.png
這個做法也符合了題目開頭提到"不能使用額外的空間"的部份

參考資料

參考1LeetCode专题-Python实现之第26题:Remove Duplicates from Sorted Array


上一篇
#26 Remove Duplicates from Sorted Array
下一篇
#141 Linked List Cycle
系列文
Leetcode新手挑戰30天31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言