iT邦幫忙

2025 iThome 鐵人賽

0
自我挑戰組

leetcode系列 第 27

leetcode 27. Remove Element

  • 分享至 

  • xImage
  •  

題目:
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所有出現的。元素的順序可以改變。然後傳回中不等於 的元素個數。valnums numsval

考慮中元素的數量nums不等於val,k為了被接受,您需要做以下事情:

改變數組nums,使 的前幾個k元素nums包含不等於 的元素val。 的其餘元素nums以及 的大小並不重要nums。
返回k。
題目說明

給定一個整數陣列 nums 和一個整數 val,
要求就地移除所有數值等於 val 的元素,並返回移除後的新長度。

不要使用額外的陣列空間。你必須在原地修改輸入陣列
https://ithelp.ithome.com.tw/upload/images/20251020/20169340pEM9YtLhKT.png
解題思路
使用 slow 來標記有效元素的最後位置。

遍歷陣列的每個元素:

若 nums[i] != val,就把它放到 nums[slow] 並讓 slow++。

若相等則跳過。

結束後,slow 即為新陣列長度。


上一篇
leetcode 26. Remove Duplicates from Sorted Array
下一篇
leetcode 28 Find the Index of the First Occurrence in a String
系列文
leetcode30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言