-
Notifications
You must be signed in to change notification settings - Fork 86
Open
Description
原题链接:https://leetcode-cn.com/problems/move-zeroes/
参考题解了动画演示 283.移动零的一次遍历解法。
解题思路:
- 快指针遍历数组。慢指针表示存放非0元素的位置
- 快指针遍历到非0元素时,将其移动到慢指针位置,并将慢指针加1
时间复杂度:O(n)
空间复杂度:O(1)
/**
* @param {number[]} numbers
* @return {void} Do not return anything, modify numbers in-place instead.
*/
var moveZeroes = function (numbers) {
// 非零值需要移动到的位置,其位置始终是最前一个待安放非零元素的位置
let moveIndex = 0;
numbers.forEach((value, index) => {
// 如果当前值不为0,则需要将其向前移动
if (value !== 0) {
// 避免特殊情况,如数组只有1个值时,将其值错误赋值为0
if (moveIndex !== index) {
// 将当前值移动到前排
numbers[moveIndex] = value;
// 将当前值设置为0,完成值的对调
numbers[index] = 0;
}
// 移动完之后,将指针移动到下一个需要移动的位置
moveIndex++;
}
});
};Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels