一、题目描述:
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12] 输出: [1,3,12,0,0]
引自:leetcode-cn.com/problems/mo…
题目链接:283. 移动零
二、思路分析:
用 noZeroCount 记录非0元素的数量 ;
遍历数组中不为0的元素依次数组的前边挪 并且用 noZeroCount 控制数组索引赋值;
上述流程执行完后,把从 noZeroCount 一直到 数组的数量减一 的位置元素赋值为0。
三、AC 代码:
class Solution {
func moveZeroes(_ nums: inout [Int]) {
// 空数组直接返回
if (nums.count < 1) {
return;
}
// 用 noZeroCount 记录非0元素的数量
// 遍历数组中不为0的元素依次数组的前边挪 并且用 noZeroCount 控制数组索引赋值
var noZeroCount : Int = 0;
for index in 0..<nums.count {
if (nums[index] != 0) {
nums[noZeroCount] = nums[index];
noZeroCount += 1;
}
}
// 从 noZeroCount 一直到 数组的数量减一 的位置元素赋值为0
for index in noZeroCount..<nums.count {
nums[index] = 0;
}
}
}
四、参考学习网址
本文正在参与「掘金 3 月闯关活动」, 点击查看 活动详情