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

移动零 #27

Open
Aras-ax opened this issue Apr 1, 2019 · 0 comments
Open

移动零 #27

Aras-ax opened this issue Apr 1, 2019 · 0 comments

Comments

@Aras-ax
Copy link
Owner

Aras-ax commented Apr 1, 2019

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

示例:

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

说明:

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

解答

function moveZeroes(nums){
    let count = 0;
    for(let i = 0, l = nums.length; i < l; i++){
        if(nums[i] === 0){
            count++;
        }else if(count > 0){
            nums[i - count] = nums[i];
            nums[i] = 0;
        }
    }
}
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