silver-hands / sss

0 stars 0 forks source link

【Q064】面试题21. 调整数组顺序使奇数位于偶数前面 #64

Open fly0o0 opened 4 years ago

fly0o0 commented 4 years ago

面试题21. 调整数组顺序使奇数位于偶数前面

fly0o0 commented 4 years ago
/**
 * @param {number[]} nums
 * @return {number[]}
 */
var exchange = function(nums) {
  let low = 0
  let fast = 0

  while (fast < nums.length) {
    if (nums[fast] % 2 != 0) {

      // 把奇数往前交换
      [nums[fast], nums[low]] = [nums[low], nums[fast]]

      // 奇数部分增加1
      low++
    }
    // 遍历增加1
    fast++
  }

  return nums
};