27 Remove Element

題目解析

原題是給定一個名叫nums的陣列,一個名叫val的整數。要刪掉nums裡的指定的val,並回傳刪掉後原nums長度大小。

舉例 : [2,3,8,8,2] , 8 ,就是陣列裡8不要 ==> [2,3,2] 長度為3,回傳3即可

原題目描述:

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory

這句話是說不要new一個新的陣列,只需modifying看起來只要overwrite即可且要符合O(1)。因為題目是「Remove Element」,所以我一直搞不懂要怎麼解題。就算看別人解題也是看不懂,不曉的為何只是替換陣列裡與val相同的值,而不是刪掉?題目不是要我們刪掉陣列元素嗎?

後來看到LeetCode in Python 27. Remove Element - Michelle小梦想家 ,在解說題目描述部分才了解原來下面的

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

原來下面澄清我沒看到,原來這個主函數是如何使用我們的方法( removeElement(int[] nums, int val) )的。1

1 首先我們的方法會回傳長度給len。

2 下面的for 迴圈會跑到len長度,且會把nums[i]印出來。這樣就可以說明為何要替換原nums的元素(把與val相同的元素用其它的元素蓋過)

舉例 :

   //[3,2,2,3]
    //[2,2,3,3]
    //for (int i = 0; i < len; i++) {
    // print(nums[i]);
    //}
    // output [2,2]

Last updated

Was this helpful?