0027 - Remove Element

大意

移除陣列裡的特定數字,回傳剩餘數量的整數。

輸出不看排序,只要內容對就好,例如以下題幹:

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

詳細說明

因為自己卡關卡太久了,就直接看解答。

其實只要反向思考,解題策略就會跟 0026  差不多。

class Solution {
    public int removeElement(int[] nums, int val) {
        int nonTargetIndex = 0;

        for(int i = 0; i < nums.length; i++){
            if(nums[i] != val){
                nums[nonTargetIndex] = nums[i];
                nonTargetIndex += 1;
            }
        }

        return nonTargetIndex;
    }
}

Revision #2
Created 8 July 2024 03:05:57 by Nesquate
Updated 8 July 2024 03:18:28 by Nesquate