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. 移动零 #6

Open
Geekhyt opened this issue Jan 23, 2021 · 0 comments
Open

283. 移动零 #6

Geekhyt opened this issue Jan 23, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Jan 23, 2021

原题链接

双指针

题目要求将所有 0 移动到数组的末尾,同时还要保持非零元素的相对顺序。

在此基础上附加了两个条件:

1.必须在原数组上操作,不能拷贝额外的数组。
2.尽量减少操作次数。

我们可以借助双指针来进行求解,求解过程如下:

1.初始化双指针 i 、j 指向数组头部索引 0。
2.将 i 指针不断向右移动,j 指针负责提供交换的位置,当遇到非 0 数字时,将两个指针位置的数字交换,同时继续向右边移动两个指针。这样交换可以保证题目要求的非 0 数字相对顺序不变。
3.当遇到 0 时,向右移动 i 指针,j 指针不动。
4.循环完成时即可将所有的 0 移动到数组的末尾。

const moveZeroes = function (nums) {
    let i = 0, j = 0;
    while (i < nums.length) {
        if (nums[i] != 0) {
            [nums[i], nums[j]] = [nums[j], nums[i]];
            i++;
            j++;
        } else {
            i++;
        }
    }
}
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)
@Geekhyt Geekhyt added the 简单 label Jun 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant