27. Remove Element
給定一個整數數組 nums 和一個整數 val,就地移除 nums 中所有出現的 val。元素的順序可以改變。然後返回 nums 中不等於 val 的元素的數量。
假設 nums 中不等於 val 的元素數量為 k,為了被接受,你需要做以下幾件事:更改數組 nums,使得 nums 的前 k 個元素包含不等於 val 的元素。
nums 剩餘的元素不重要,數組的大小也不重要。
返回 k。
自定義測試:
測試將使用以下代碼來檢查你的解決方案:
int[] nums = [...]; // 輸入數組
int val = ...; // 要移除的值
int[] expectedNums = [...]; // 預期答案的正確長度。
// 它被排序且沒有等於 val 的值。
int k = removeElement(nums, val); // 調用你的實現
assert k == expectedNums.length;
sort(nums, 0, k); // 將 nums 的前 k 個元素排序
for (int i = 0; i < actualLength; i++) {
assert nums[i] == expectedNums[i];
}
如果所有斷言都通過,那麼你的解決方案將被接受。
範例 1:
輸入:nums = [3,2,2,3], val = 3 輸出:2, nums = [2,2,_,_] 解釋:你的函數應返回 k = 2,nums 的前兩個元素為 2。 返回的 k 之後的元素無關緊要(因此它們是下劃線)。
Python
from typing import List
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
# Initialize the write pointer
write_index = 0
for i in range(len(nums)):
if nums[i] != val:
nums[write_index] = nums[i]
write_index += 1
return write_index
16.46MB, 38ms
C++
#include <vector>
using namespace std;
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
// Initialize the write pointer
int write_index = 0;
// Iterate through the array
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] != val) {
nums[write_index] = nums[i];
++write_index;
}
}
return write_index;
}
};
10.54MB, 2ms
Javascript
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
// Initialize the write pointer
let writeIndex = 0;
// Iterate through the array
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== val) {
nums[writeIndex] = nums[i];
writeIndex++;
}
}
return writeIndex;
};
48.91MB, 54ms