leetcode-27-remove-element
題目
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
- Change the array
numssuch that the firstkelements ofnumscontain the elements which are not equal toval. The remaining elements ofnumsare not important as well as the size ofnums. - Return
k. - 題目連結
Example 1
1 | Input: nums = [3,2,2,3], val = 3 |
Example 2
1 | Input: nums = [0,1,2,2,3,0,4,2], val = 2 |
解釋題目
給你一個 array ( 叫 nums ),跟要去除的數字 ( 叫 val ),題目的條件是不能用新的 array 紀錄,只能更動原本的 array,也就是 in-place 的方式,最後,要回傳 array 中,沒有被移除的數字數量,假設為 k。驗證答案時,只會取 array 中前 k 個值,k 之後的值不會影響驗證。
思路
- 在一次的 for 迴圈中,把 array 重新排列
- 因為要重新排列 array,所以必須有一個 new_index 去記錄 array 中每個位置,要放甚麼數字
- new_index 會從 0 開始
- 遍歷 array 的過程中
- 如果
array[i]的值 不等於 val ( 要去除的數字 ),array[new_index]會替換成array[i],且 new_index 要往下走一步 - 如果
array[i]的值 等於 val ( 要去除的數字 ),new_index 維持原位
- 如果
圖像拆解




程式碼 (1)
1 | class Solution: |
程式碼 (2)
直覺寫法,用 python remove() 的函式。
1 | class Solution: |
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 雜耍特技師!








