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

移动零 #3

Open
yoluxi opened this issue Aug 1, 2019 · 4 comments
Open

移动零 #3

yoluxi opened this issue Aug 1, 2019 · 4 comments
Labels
algorithm algorithm

Comments

@yoluxi
Copy link
Owner

yoluxi commented Aug 1, 2019

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

示例:

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

说明:

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

yoluxi commented Aug 1, 2019

var moveZeroes = function(nums) {
   return nums.reduce((previousValue, currentdValue, currentIndex, arr) => {
        if (currentdValue === 0) {
            previousValue.splice(currentIndex, 1)
            previousValue.push(0)
        }
        return previousValue
    }, nums) 
}

@yoluxi
Copy link
Owner Author

yoluxi commented Aug 1, 2019

var moveZeroes = function(nums) {
    let i = 0;
    let boundary = nums.length
    for ( ; i < boundary; i++) {
        if (nums[i] === 0) {
            nums.splice(i, 1)
            nums.push(0)
            --i
            --boundary
        }
    }
};

@yoluxi
Copy link
Owner Author

yoluxi commented Aug 1, 2019

var moveZeroes = function(nums) {
   return nums.reduce((previousValue, currentdValue, currentIndex, arr) => {
        if (currentdValue === 0) {
            previousValue.splice(currentIndex, 1)
            previousValue.push(0)
        }
        return previousValue
    }, nums) 
}

[0, 0, 0, 3, 12] => [ 0, 3, 12, 0, 0 ]

@yoluxi
Copy link
Owner Author

yoluxi commented Aug 1, 2019

 let i = -1;
 let j = 0;
 let boundary = nums.length
  while ( j < boundary ) {
        if (nums[j] !== 0) {
            nums[++i] = nums[j]
        }
        j++
    }
     for ( i += 1; i < boundary; i++ ) {
        nums[i] = 0
    }

@yoluxi yoluxi added the algorithm algorithm label Aug 2, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
algorithm algorithm
Projects
None yet
Development

No branches or pull requests

1 participant