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

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

Open
hanyueqiang opened this issue Dec 21, 2020 · 0 comments

Comments

@hanyueqiang
Copy link
Owner

示例:

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

说明:
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
解法1:

function zeroMove(array) {
  let len = array.length;
  let j = 0;
  for (let i = 0; i < len - j; i++) {
    if (array[i] === 0) {
      array.push(0);
      array.splice(i, 1);
      i--;
      j++;
    }
  }
  return array;
}
console.log(zeroMove(arr1))

解法2

function moveZero(arr) {
  let len = arr.length - 1;
  let flag = false;
  while (len > -1) {
    if (flag) {
      if (arr[len] === 0) {
        arr.splice(len, 1)
        arr.push(0)
      }
    } else {
      if (arr[len] !== 0) {
        flag = true
      }
    }
    len--
  }
  return arr
}
console.log(moveZero(arr1))
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