Image From LeetCodeImage From LeetCode

今天我們要講解的是 [Remove Element],這在 LeetCode 算是比較簡單的題目,讓我們一起開始吧!

進來之前請先注意,我的方式不一定完全正確,只是依照我自己的理念進行撰寫,所以如果程式上有什麼更好的解法,歡迎提出見解。

這次題目

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 nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
  • Return k.

Custom Judge:

The judge will test your solution with the following code:

1
2
3
4
5
6
7
8
9
10
11
12
int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
// It is sorted with no values equaling val.

int k = removeElement(nums, val); // Calls your implementation

assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
assert nums[i] == expectedNums[i];
}

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

Example

1
2
3
4
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
1
2
3
4
5
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).

Constraints:

  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 50
  • 0 <= val <= 100

自已解法

這個題目主要是針對nums陣列裡的值,判斷是否等於val,相等的話把該值移動到最後方,並且計算不重複值有多少也就是k,接著上方的驗證結果會依據nums進行0 -> k來進行排列,判斷是否為預期的值。

首先我們先建立k值,接著讓他回傳。

1
2
3
4
5
var removeElement = function(nums, val) {
let k = 0;

return k;
};

接下來我們透過for-loop來進行位置上的調整,我們可以把k當作一個錨點,當不相等時,我們可以透過num[k]來進行覆蓋,如此一來前排就能取得不相等的陣列,然後k+1之後的值我們就不管他,因為他驗證只會針對0->k

1
2
3
4
5
6
7
8
9
var removeElement = function(nums, val) {
let k = 0;
for(let i = 0; i < nums.length; i++) {
if (nums[i] != val) {
nums[k++] = nums[i];
}
}
return k;
};

實作結果

這個題目跟上一篇題目蠻像的,上一篇是使用交換的機制,而這次是直接進行覆蓋。

Image From LeetCodeImage From LeetCode