LoginSignup
0
1

More than 1 year has passed since last update.

【LeetCode】就活に向けたコーディングテスト対策 #09

Last updated at Posted at 2021-06-18

はじめに

こんばんは.
M1就活生がLeetCodeから,easy問題を中心にPythonを用いて解いていきます.

↓では,解いた問題のまとめを随時更新しています.
まとめ記事

問題

今回解いたのは,難易度easyから 問題27のRemove Element です.
問題としては,リストnumsから,整数valを全て削除し,最終的なリストnumsの個数を返すというもの.

入力例と出力例は以下の通りです.

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).

書いたコード

今回の問題は,前回とほとんど変わらない問題でした.リストの指定した要素を削除するものとしてremove()があります.しかし,remove()では,指定した最初の要素のみを削除するため,val以外の値をリストとして返す,リスト内包表記を使いました.なお,リスト内包表記においても,新しいlistオブジェクトを生成するため,リストのスライスを用いることで,元のリストの中身を書き換えています.

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        nums[:] = [num for num in nums if num != val]
        return len(nums)

おわりに

リスト内包表記を使うと,可読性が欠けてしまう場合があります.時と場合を考えてうまく使いこなしていきたいものです.

今回書いたコードはGitHubにもあげておきます.

前回 次回

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1