Voyz's Studio.

LeetCode算法笔记--移动零

字数统计: 148阅读时长: 1 min
2021/01/06 Share

LeetCode算法笔记-Day59

283. Move 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.

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

1
2
3
4
5
Example:

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

方法一:双指针

Analyse:

交换零.gif

Answer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = (nums) => {
let j = 0
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
let _tmp = nums[j]
nums[j] = nums[i]
nums[i] = _tmp
j++
}
}
}
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)
CATALOG
  1. 1. LeetCode算法笔记-Day59
    1. 1.1. 283. Move Zeroes
    2. 1.2. 方法一:双指针
      1. 1.2.1. Analyse:
      2. 1.2.2. Answer: