Try  HackMD Logo HackMD

Leetcode 27 Array List Remove element

My Solution (remove會比較慢)

def removeElement(self, nums, val):
    last_index = len(nums)-1
    i = 0
    while (i <= last_index):
        if nums[i] == val:
            nums.remove(val)  ## 因為remove 掉 後一個數自動往前
            last_index -= 1
        else:
            i+=1
    print(nums,i)
    return len(nums)

Best Solution
time:O(n) space:O(1)

def removeElement(self, nums, val):
    last_index = len(nums)-1
    i,j = 0 ,0
    while ( j <=last_index ):
        if nums[j] == val:
            # 把要刪除的丟到最後
            nums[j],nums[last_index] = nums[last_index],nums[j] 
            last_index -=1  # 最後index-1 代表不會在找尋到他
            continue
        else:
            i += 1
        j+=1
    print(nums[:i])
    return i
tags: LeetCode remove