移动零

57 阅读1分钟

要求

1 To implement a function that move ALL the 0s to the end of given array,maintaining the order of other elements.
2 Hint: if the input array is empty, you should return an empty array as well.

Example 1:

Input:[1,0,1,2,0,1,3]
Output:[1,1,2,1,3,0,0]

题解

const solution1 = (arr) => {
  let slowIndex = 0;
  for (let fastIndex = 0; fastIndex < nums.length; fastIndex++) {
    if (nums[fastIndex] !== 0) {
      [nums[slowIndex], nums[fastIndex]] = [nums[fastIndex], nums[slowIndex]];
      slowIndex++;
    }
  }
};