Leetcode 0283. 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.
Description
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.
Example 1:
Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0]
Example 2:
Input: nums = [0] Output: [0]
Constraints:
1 <= nums.length <= 10^4
-2^31 <= nums[i] <= 2^31 - 1
Follow up:
- Could you minimize the total number of operations done?
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
# Iteration
# Time Complexity: BigO(N)
# Space Complexity: BigO(N)
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
index = 0
for i in nums:
if i != 0:
nums[index] = i
index += 1
for i in range(index, len(nums)):
nums[i] = 0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* Do not return anything, modify nums in-place instead.
* Iteration
* Time Complexity: BigO(N)
* Space Complexity: BigO(1)
*/
function moveZeroes(nums: number[]): void {
let zeros = nums.filter((num) => num == 0).length;
for (let i = 0; i < nums.length; i++) {
if (nums[i] == 0 && zeros != 0) {
let zero = nums.splice(i, 1)[0];
nums.push(zero);
zeros -= 1;
i -= 1;
}
}
}
This post is licensed under CC BY 4.0 by the author.