移动零

kingcwt2023-09-23前端算法 基础数据结构 面试题

要求

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++;
    }
  }
};
Last Updated 10/16/2023, 7:06:22 AM
What do you think?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
Comments
  • Latest
  • Oldest
  • Hottest
Powered by Waline v2.15.8