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;
}
}
- 設定一個紀錄非移除目標的 Target Index
- 迭代目前的整數陣列
- 如果目前迭代整數不等於要移除的目標,將它複製至非移除目標的 Target Index,Target Index 移動到下一個位置
- 重複此過程直到迭代結束,回傳非移除目標的值
No Comments