問題如下:
給定一個整數陣列 nums 和一個整數 val,刪除 nums 中所有出現的 val 就地。元素的順序可以改變。然後傳回 nums 中不等於 val.
的元素個數考慮 nums 中不等於 val 的元素數量為 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).
這是我解決的方法:
為了解決這個問題,我使用了兩個主要策略:
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
這是完整的解決方案:
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中文網其他相關文章!