Leetcode Day 刪除元素解釋

WBOY
發布: 2024-07-16 19:46:46
原創
1034 人瀏覽過

Leetcode Day Remove Element Explained

問題如下:

給定一個整數陣列 nums 和一個整數 val,刪除 nums 中所有出現的 val 就地。元素的順序可以改變。然後傳回 nums 中不等於 val.

的元素個數

考慮 nums 中不等於 val 的元素數量為 k,要被接受,您需要執行以下操作:

  • 改變陣列 nums,使 nums 的前 k 個元素包含不等於 val 的元素。 nums 的其餘元素以及 nums 的大小並不重要。
  • 返回k。

自訂法官:

法官將使用以下程式碼測試您的解決方案:

int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
                            // It is sorted with no values equaling val.

int k = removeElement(nums, val); // Calls your implementation

assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
    assert nums[i] == expectedNums[i];
}
登入後複製

如果所有斷言都通過,那麼您的解決方案將被接受。

範例1:

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
登入後複製

範例2:

Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).
登入後複製

這是我解決的方法:

為了解決這個問題,我使用了兩個主要策略:

  1. 就地替換:不要建立新陣列來儲存不等於val的元素,而是使用相同的陣列nums覆蓋需要移除的元素。
  2. 雙指標技術:一個指標 (i) 迭代數組中的每個元素,另一個指標 (k) 追蹤下一個非 val 元素應放置的位置。
  • 首先,初始化指標 k 並將其設為 0。這將追蹤下一個非 val 元素應放置的位置。
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:       
    k = 0
登入後複製
  • 迭代 nums 陣列。
  • 檢查當前元素 nums[i] 是否與 val 不同以追蹤 k。
  • 如果是,則將元素 nums[i] 移到第 k 個位置,並將 k 加 1 以更新下一個非 val 元素的位置。
for i in range(len(nums)):
    if nums[i] != val:
        nums[k] = nums[i]
        k += 1
登入後複製
  • 傳回k,即不等於val的元素個數。
return k
登入後複製

這是完整的解決方案:

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

以上是Leetcode Day 刪除元素解釋的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!