ほぼ日刊競プロ leetcode 283. Move Zeroes

283. Move Zeroes

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.

考えたこと

新しい配列を作らずに,配列の中身を入れ替える必要がある.初めにバブルソートでやったら時間が足りず失敗した.

class Solution:
   def moveZeroes(self, nums: List[int]) -> None:
       """
       Do not return anything, modify nums in-place instead.
       """
       change = True
       for i in range(len(nums)):
           if not change: 
               break
           change = False  
           for j in range(len(nums) - i -1):
               if nums[j] ==0: 
                   nums[j], nums[j+1] = nums[j+1], nums[j] #前後入れ替え
                   change = True 
       return nums


次にlistを後ろから探索することにした.後ろから探し,0が見つかれば消し,appendすることで一番後ろに0をくっつけることになると考えた.

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

この記事が気に入ったらサポートをしてみませんか?