オットセイの経営日誌

データサイエンス系ベンチャーを経営してます。経営のこと、趣味のことつぶやきます。

LeetCode / Remove Element

https://leetcode.com/problems/remove-element/

Given an array nums and a value val, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example 1:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length.

Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2,
Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
Note that the order of those five elements can be arbitrary.
It doesn't matter what values are set beyond the returned length.

前回の記事と類似の問題です。
指定された値をリストから取り除く問題です。これだけなら簡単すぎて問題になりませんが、入力のリストを直接修正する必要があります。

また、相変わらず以下に留意する必要があります。気をつけましょう。。。
入力のリストnumsに対して、関数の返り値はリストの要素数nで、正解を判定する対象はnums[:n]になる

回答・解説

解法1

リストの要素数分ループを回していき、除外対象の値valでない値が見つかったら、リストの前から順に値を置き換えていきます。
変数countを初期値0のポインタとし、値の置換場所を指し示すものとして使います。
nums = [3,2,2,3], val = 3
の場合、2度目のループで3でない値(2)が見つかるので、nums[count]を2で置き換えます。
ポインタをcount += 1で1つ進めて、次の処理に移ります。

最終的に正解を判定する対象は、nums[:count]になります。

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

今日は非常に簡単な問題でした。まあ祝日なので、このくらいの軽さで。