Pythonフォースボタンブラッシングレコード-283。ゼロ移動

トピック:

numsの配列が与えられた場合、ゼロ以外の要素の相対的な順序を維持しながら、すべてのゼロを配列の最後に移動する関数を記述します。
ここに写真の説明を挿入

方法1:
実行時間:192ミリ秒
メモリ消費量:14.1 MB

リストを使用する組み込みの方法は非常に単純で、遅すぎます

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        for i in nums:
            if i == 0:
                nums.remove(i)
                nums.append(i)

方法2:
実行時間:36ミリ秒
メモリ消費量:14 MB

ダブルポインター方式:
iを使用して、ゼロ以外の位置を記録します。ゼロ以外の要素に遭遇すると、要素を左に移動します。jを使用して、位置iの要素を左に移動する場所を記録します。ゼロ以外のすべての要素をトラバースする場合、残りの位置には値0が割り当てられます。スペースの複雑さはO(n)です
ここに写真の説明を挿入

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        i, j = 0, 0
        while i < len(nums):
            if nums[i]:
                nums[j] = nums[i]
                j += 1
            i += 1
        while j < len(nums):
            print(j)
            nums[j] = 0
            j += 1

方法3:
実行時間:44ミリ秒
メモリ消費量:14 MB

キーはソート基準を指定します

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        nums.sort(key=lambda x:x==0)

上記のコード行はどういう意味ですか?
次の例を見ると理解できます

nums = [0, 1, 0, 3, 12, 1]
def a(x):
    return x==1
nums.sort(key=a)
print(nums)  ##打印输出  nums = [0, 0, 3, 12, 1, 1]

print("==========================================")
nums1 = [0, 1, 9, 3, 1, 12, 1]
def b(x):
    return x==1

nums1.sort(key=b, reverse=True)
print(nums1)  ## 打印输出  nums1 = [1, 1, 1, 0, 9, 3, 12]

おすすめ

転載: blog.csdn.net/weixin_45455015/article/details/110790256
おすすめ