5 DERECHA

283. Move Zeroes ( 배열 위치 변화 ) 본문

카테고리 없음

283. Move Zeroes ( 배열 위치 변화 )

kay30 2021. 7. 8. 17:14
문제 접근

They given to us "nums" array like this.

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:

In this array, there are some '0' integer.

So all we have to do is that we should move zeroes from the original position to end of the array.

And we have to take care about space Big-O and time Big-0 notation.

So I would like to not declare another array. 

Instead of  this, I will declare two global variables.

One of them's name is 'cnt', and I will add this variable when I met zeroes during I search the given array "nums".

And I will declare 'k' valriable to use as a idx of nums so that we can store integers except zeroes in nums.

You can see my code below the text.

 

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        cnt = 0
        k = 0
        for x in nums:
            if x==0:
                cnt +=1
            else:
                nums[k] = x
                k+=1
        for i in range(len(nums)-1,len(nums)-cnt-1,-1):
            nums[i] = 0