Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

283. 移动零 #73

Open
webVueBlog opened this issue Sep 5, 2022 · 0 comments
Open

283. 移动零 #73

webVueBlog opened this issue Sep 5, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

283. 移动零

Description

Difficulty: 简单

Related Topics: 数组, 双指针

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

请注意 ,必须在不复制数组的情况下原地对数组进行操作。

示例 1:

输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]

示例 2:

输入: nums = [0]
输出: [0]

提示:

  • 1 <= nums.length <= 104
  • -231 <= nums[i] <= 231 - 1

**进阶:**你能尽量减少完成的操作次数吗?

Solution

Language: JavaScript

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
// 双指针
// 快指针一直移动
// 慢指针只在快指针遇到非 0 元素的时候移动
// 即 只要快指针碰到 0 就在原地待一下
// 且在移动之前脚下的 0 与快指针脚下的值交换一下
// 最后效果就是:慢指针左边没 0,右边一直到快指针区间都是 0

var moveZeroes = function (nums) {
	let slow = 0,
		fast = 0;
	while (fast < nums.length) {
		if (nums[fast] !== 0) {
            [nums[fast], nums[slow]] = [nums[slow], nums[fast]];
            slow++;
		}
		fast++;
	}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant