November 5, 2023

Viiisit [LeetCode] - 27. Remove Element

#javascript#ruby

keep learning, keep coding!

Problem - 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:

翻譯蒟蒻

題目要求要更改原始的 nums 陣列,最終的 k 值要返回陣列中不等於 val 元素的數量。


Solution - JavaScript

Solution 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
for (let i = 0; i < nums.length; i++){
if (nums[i] === val) {
// 找到相同的元素之後要從原始陣列 nums 中移除
nums.splice(i, 1);
// 因為有從原始陣列 nums 中移除一個元素,需要將 i 減一,這樣下一次循環才會檢查當前索引的元素。
i--;
}
}
};

Solution 2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
let index = 0;
for (let i = 0; i < nums.length; i++){
if (nums[i] !== val) {
nums[index++] = nums[i];
}
}
return index;
};

Solution - Ruby

1
2
3
4
5
6
7
8
9
10
11
12
def remove_element(nums, val)
# 刪除 num == val
nums.delete(val)
# 回傳 nums 的長度
nums.length
end

nums = [1, 2, 3, 2, 4]
val = 2

result = remove_element(nums, val)
puts result

LeetCode 傳送門 - Remove Element