Site icon May's Notes

[LeetCode] 27. Remove Element (JS)

LeetCode Sharing

題目

給定一個整數陣列 nums 和一個整數 val,要求將陣列中所有等於 val 的元素移除,並傳回移除後數組的新長度 k。

需要注意的是題目要求 in-place,所以不能新增其他的陣列來保存結果。

Example 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).

Example 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. 使用 pointer 來遍歷陣列中的每一個元素。
  2. 如果當前元素 nums[index] 不等於 val,就把這個元素放到 nums[pointer],然後移動 pointer
  3. 遍歷完陣列後,pointer 的位置就是新陣列的長度,即不等於 val 的元素個數。
/**
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
var removeElement = function(nums, val) {
    let pointer = 0
    for (let index = 0; index < nums.length; index++) {
        if (nums[index] !== val) {
            nums[pointer] = nums[index]
            pointer++
        }
    }
    return pointer
};

送出時只會檢查 nums 前 n 個元素是否符合題目需求(n = 你最後回傳的個數)

Exit mobile version