27. Remove Element

Leetcode

題目

Given an integer array nums and an integer val, remove all occurrences of val in nums in-placearrow-up-right. The relative order of the elements may be changed.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-placearrow-up-right with O(1) extra memory.

Custom Judge:

The judge will test your solution with the following code:

If all assertions pass, then your solution will be accepted.

Example 1:

Example 2:

解答

  • 方法一 - Two pointer

這題需要排除等於 val 的數字,因此我們可以從頭開始遍歷,只要找到等於 val 的數字一律與矩陣後面的數字交換,這樣整個遍歷完後,不需要的數字都會放到後面了

這裡我們使用左指針與右指針的方式判斷,如果當下元素等於 val 就代表這個元素要與右指針的元素交換並且交換完後將右指針往前移動,那如果不等於 val 的話就將左指針往後移動

Runtime: 63 ms Beats 10.20% of users with JavaScript

Memory: 49.13 MB Beats 17.43% of users with JavaScript

  • 方法二

當遇到要移除的元素時,繼續往後找後面不需移除的元素,並賦值到這個要被移除元素的 index 上

Runtime: 57 ms Beats 34.56% of users with JavaScript

Memory: 48.86 MB Beats 55.86% of users with JavaScript

  • 方法三 - Splice

單純利用 js 的 splice 方法來移除元素

Runtime: 57 ms Beats 34.56% of users with JavaScript

Memory: 48.86 MB Beats 55.86% of users with JavaScript

測資

Last updated