给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例 1:
Input: nums = [0,1,0,3,12]Output: [1,3,12,0,0]
示例 2:
Input: nums = [0]Output: [0]
提示:
- 1 ≤
nums.length≤ 10; - -2 ≤
nums[i]≤ 2-1;
思路
Rust实现,使用双指针法。
快指针从头遍历到尾,当遇到非零的数时,就和慢指针的值交换;
当快指针遇到0时,直接跳过走下一个元素;
快指针遍历完后,再让慢指针从当前位置遍历到尾巴,把剩下的数都置0。
代码
Rust:
// 0ms, 2MBimpl Solution {pub fn move_zeroes(nums: &mut Vec<i32>) {let mut slow_index = 0;for fast_index in 0 .. nums.len() {if nums[fast_index] != 0 {nums[slow_index] = nums[fast_index];slow_index += 1;}}for k in slow_index .. nums.len() {nums[k] = 0;}}}
