283. Move Zeroes
https://leetcode.com/problems/move-zeroes/description/
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.
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.
Thoughts
把数组中非零元素移到前面。也就是第一个非零元素放到0位置,第二个非零在1...依次类推,因此用两个前后i和j指针分别对nums遍历和指向要插入的位置,当非零时插入到j并++。
Code
Analysis
做题耗时9min.
Errors:
以为非零都是正整数。
时间复杂度O(n). 空间O(1).
Last updated
Was this helpful?