[LeetCode] Challenge log 283

283. Move Zeros

The key is to use no extra space, hence swap is most convenient. To optimize operation, only swap when encounter zeroes.


Given an array nums, write a function to move all 0‘s to the end of it while maintaining the relative order of the non-zero elements.

Example:

1
2
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

Soulution:

standard solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
cur = 0
tail = 0
n = len(nums)
while cur < n:
if nums[cur] != 0:
nums[cur], nums[tail] = nums[tail], nums[cur]
tail += 1
cur += 1

my solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if nums == []: return []
n = len(nums)
i = 0
while i < n :
if nums[i] == 0:
del nums[i]
nums.append(0)
n -= 1
i -= 1
i += 1
0%