Welcome 歡迎光臨! 愛上網路 - 原本退步是向前

原地刪除重複出現的元素 LeetCode:26

題目的意思,給一個排序好的陣列(array),消除其中重複的數字,然後回傳新的陣列的長度。不允許建立新的陣列。必須透過回傳一個固定的數字,來表示陣列的長度。

nums = [0,0,1,1,1,2,2,3,3,4]
Your function should return length = 5, 
with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respective

 

def remove_Duplicates(nums):
    if len(nums) < 2:
        return len(nums)
    print(nums)
    x=0
    y=1
    while y
        if (nums[y]==nums[x]):
            nums[y]=""  //清除相同值
            y=y+1
        else:
            x=x+1  //不同值往前一個 準備記錄下一個一值
            nums[x]=nums[y]  //記錄目前不同值
            nums[y]=""            //清除已經被記錄的值          
            y=y+1
    print(nums)
    return x+1


nums = [0,0,1,1,1,2,2,3,3,4]
remove_Duplicates(nums)
 

TIPS 

Y=移動指標

X=記錄不同值指標 不同部份往前記錄

 

https://medium.com/@urdreamliu/26-%E5%9C%96%E8%A7%A3-remove-duplicates-from-sorted-array-cbee5b2d4df8

[ Python ] 瀏覽次數 : 28 更新日期 : 2024/07/28