iT邦幫忙

0

[LeetCode] 自我挑戰 #27 Remove Element

Remove Element

https://ithelp.ithome.com.tw/upload/images/20230610/20160759LDen5tUKGl.png

題目說明

給定一組整數陣列和一個整數val,需求是刪掉陣列中所有val的數,不在意是否有排序。
特別注意的是,需要將不是val的k個元素放在陣列的前k個,並回傳k(共幾個元素)

範例

Example 1:
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).

Example 2:
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).

限制條件

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

思路

想法上與曾經做過的#88類似,比對陣列中每一個值,只要不是val(代表需要留下),就把它從開頭依序存到陣列裡,最後當前存到的位置就是不為val的最後一個index,回傳數量即可。

C++ 程式碼

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int k = 0;
        for(int i = 0; i< nums.size(); i++){
            if(nums[i] != val){
                nums[k] = nums[i];
                k++;
            }
        }
        return k;
    }
};

Python3 程式碼

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

另解

看到題目當下,覺得既然不在意順序及大小那就直接刪掉不想要的值,再回傳當前大小即可,但效能上好像沒有上一個解法來得好。
※ 因為 nums 被 erase 刪掉值後,後面的數會往前挪,所以要再檢查一次同個位置,故將 i - 1。

C++ 程式碼

小補充 經過 erase() 後,size 會改變但 capacity 不變

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        for (int i=0; i<nums.size(); i++) {
            if (nums[i] == val) {
                nums.erase(nums.begin()+i);
                i--;
            }
        }
        return nums.size();
    }
};

Python3 程式碼

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        while val in nums:
            nums.remove(val)
        return len(nums)

其實本來要仿照c++寫for loop的,但不知道為甚麼index會超出範圍,還沒弄懂...就換成while寫法了
或許有人知道原因可以跟我分享~ 感謝

for i in range (len(nums)):
    if nums[i] == val:
        nums.remove(val)
        i-=1;
return len(nums)

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言