283.Move Zeroes
Tags: [overriding], [pointers]
Link: https://leetcode.com/problems/move-zeroes/#/description
Given an arraynums
, write a function to move all0
's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12]
, after calling your function,nums
should be[1, 3, 12, 0, 0]
.
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
Solution: Overriding
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if not nums:
return
real_end = 0
for n in nums:
if n:
nums[real_end] = n
real_end += 1
while real_end < len(nums):
nums[real_end] = 0
real_end += 1
Revelation:
- Overriding the positions at where its original elements are 0s.
Note:
- Time complexity = O(n), n is the number of elements of the given nums.
Solution: Pointers
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if not nums:
return
end = len(nums) - 1
index = len(nums) - 1
while index >= 0:
if nums[index] == 0:
for i in xrange(index + 1, end + 1):
nums[i - 1] = nums[i]
nums[end] = 0
end -= 1
index -= 1
Note:
- Time complexity = O(n^2), n is the number of elements in the given nums.