iT邦幫忙

0

leetcode with python:27. Remove Element

  • 分享至 

  • xImage
  •  

題目:

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

這題跟26.Remove Duplicates from Sorted Array十分相似,不過這次要return的k為非目標數(val)的個數,同時把這些數移到陣列最前面
同樣有記憶限制,不能再開其他陣列,僅能在這個陣列上進行操作
ex:[3,2,2,3],val=3 ==> return k=2 ,而此時的陣列為[2,2,x,x] (x為任意值)

和26.一樣建立指標k來記錄

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        k=0
        for i in nums:
            if i != val:
                nums[k]=i
                k=k+1
        return k

當我們偵測到該位置值不等於val時,將該值往前面放
k代表了下次遇到符合條件的值要放的index,同時也能作為最後的回傳值
由於實在跟26.太過相似,所以解釋精簡許多
最後執行時間為35ms(faster than 89.76%)

那我們下題見


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言