LeetCode - Remove Element
今天我們要講解的是 [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 firstk
elements ofnums
contain the elements which are not equal toval
. The remaining elements ofnums
are not important as well as the size ofnums
. - Return
k
.
Custom Judge:
The judge will test your solution with the following code:
1 | int[] nums = [...]; // Input array |
If all assertions pass, then your solution will be accepted.
Example
1 | Input: nums = [3,2,2,3], val = 3 |
1 | Input: nums = [0,1,2,2,3,0,4,2], val = 2 |
Constraints:
0 <= nums.length <= 100
0 <= nums[i] <= 50
0 <= val <= 100
自已解法
這個題目主要是針對nums
陣列裡的值,判斷是否等於val
,相等的話把該值移動到最後方,並且計算不重複值有多少也就是k
,接著上方的驗證結果會依據nums
進行0 -> k
來進行排列,判斷是否為預期的值。
首先我們先建立k值,接著讓他回傳。
1 | var removeElement = function(nums, val) { |
接下來我們透過for-loop
來進行位置上的調整,我們可以把k
當作一個錨點,當不相等時,我們可以透過num[k]
來進行覆蓋,如此一來前排就能取得不相等的陣列,然後k+1
之後的值我們就不管他,因為他驗證只會針對0->k
。
1 | var removeElement = function(nums, val) { |
實作結果
這個題目跟上一篇題目蠻像的,上一篇是使用交換的機制,而這次是直接進行覆蓋。