LeetCode #27 Remove Element 移除元素

LeetCode題目翻譯

英文原文如下

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. 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-place with O(1) extra memory.

中文翻譯

給予一個整數陣列 nums 跟一個整數 val ,原地移除 nums 中出現所有的 val ,元素的相對順序可能會被改變

由於某些語言改變陣列的長度是不可能的,所以你必須將結果放在 nums 的前段部分。更正式來說,如果移除後的結果有 k 個元素,那 nums 的前 k 個元素就該是最終的答案。超過 k 個元素的部分可以被省略。

再將結果放在前 k 個元素之後,回傳 k

不要分配空間給另一個陣列,你必須要更改原先輸入陣列並使用 O(1) 的額外空間來完成。

⭐這一題跟26題肯定是同個作者,整個英文都烙烙長,後面的整段說明文字甚至一模一樣呢哈哈哈~

唯一差異就在於一個是移除所有重複的元素 (distinct),一個是移除指定的元素(數字)

範例及題目限制

一樣的說明了驗證的過程會如何進行


解題思路

這一題其實也沒甚麼特別的,要注意的是不要新增一個新的陣列,要在原有的裡面完成就是了

C# 解決方案

方案1

public class Solution {
    public int RemoveElement(int[] nums, int val) {

        int j = 0;
        for(int i=0;i<nums.Length;i++)
        {
            if(nums[i]!=val)
            {
                nums[j++] = nums[i];
            }
        }
        return j;
    }
}

可以看到這裡用了兩個變數 ji

i 的話很明顯是用來遞迴用的,而 j 則是記錄了當前更改到的索引

( 怕有人不知道,j++ 代表 j 在執行完那一行之後會+1 ,主要就是省略了在下一行寫 j+=1 的功夫)

另外,當然可以用 foreach 來取代 for loop

Java解決方案

方案1

class Solution {
    public int removeElement(int[] nums, int val) {
        
        int j = 0;
        for(int i=0;i<nums.length;i++)
        {
            if(nums[i]!=val)
            {
                nums[j++] = nums[i];
            }
        }
        return j;
    }
}

Python3 解決方案

方案1

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        j = 0
        for i in range(0,len(nums)):
            if(nums[i]!=val):
                nums[j] = nums[i]
                j+=1
        return j

熟悉Python3的小夥伴應該都知道吧,python 中並沒有 n++這種寫法

故只能分兩行寫了

JavaScript 解決方案

方案1

/**
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
var removeElement = function(nums, val) {
    var j = 0;
    for(var i=0;i<nums.length;i++)
    {
        if(nums[i]!=val)
        {
            nums[j++] = nums[i];
        }
    }
    return j;
};

結論

難易度應該算是簡單,雖然筆者在第一次寫的時候還是習慣性的多創立的一個陣列來解決哈哈

最後讓我吐槽一下標題,為什麼不改成 【Remove specific element from array】/移除陣列中的特定元素呢 !!!

這樣看起來多簡單明瞭啊

🧡如果這篇文章有幫上你的一點點忙,那是我的榮幸

🧡可以的話,幫我點個小小的廣告,我會很感謝的 (每天吃土來付主機費ing)

✅如有任何疑問,歡迎透過留言或messenger讓我知道 !

題目連結 : Remove Element – LeetCode

一些隨機文章

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *