iT邦幫忙

0

解LeetCode的學習筆記Day27_Remove Element

LFI 2025-10-18 23:38:40177 瀏覽
  • 分享至 

  • xImage
  •  

今天是紀錄LeetCode解題的第二十七天

第二十七題題目:Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
  • Return k

給定一個整數陣列nums和一個整數 val,請就地(in-place)移除nums中所有等於val的元素,元素的順序可以改變,移除後不需要保持原本順序,最後回傳nums中不等於val的元素k個

程式碼

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

執行過程

初始狀態

  • nums = [3,2,2,3]
  • val = 3

第一次執行

  • i = 0
  • j = 0
  • if nums[j] != val → 3 != 3 → False

第二次執行

  • i = 0
  • j = 1
  • if nums[j] != val → 2 != 3 → True → num[0] = num[1] = 2 → nums = [2,2,2,3]
  • i += 1 → i = 1

第三次執行

  • i = 1
  • j = 2
  • if nums[j] != val → 2 != 3 → True → num[1] = num[2] = 2 → nums = [2,2,2,3]
    • i += 1 → i = 2

第四次執行

  • i = 2
  • j = 3
  • if nums[j] != val → 3 != 3 → False

最後回傳i(也就是2),表示前2個元素是已經移除掉和val相同的元素


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言