21. Reorder the array so that the odd number precedes the even number

The title

Take an array of integers and implement a function to adjust the order of the numbers in the array so that all odd numbers are in the first half of the array and all even numbers are in the last half of the array.

Example 1

Input: nums = [1,2,3,4] output: [1,3,2,4] note: [3,1,2,4] is also one of the correct answers.Copy the code

Answer key

Double pointer

  • Define the pointer left to point to position 0
  • Define pointer right to the last digit of the array
  • If the left pointer is even and the right pointer is odd, swap the positions of the two integers as required
  • If only left is even, move right one bit to the left
  • If only left is odd, move left one bit to the right
  • Wait until left >= right to stop
  • Return the result

code

var exchange = function (nums) {
  let left = 0
  let right = nums.length - 1

  while (left < right) {
    if (nums[left] % 2= = =0 && nums[right] % 2! = =0) {
      ;[nums[left], nums[right]] = [nums[right], nums[left]]
      left++
      right--
    } else if (nums[left] % 2= = =0) {
      right--
    } else {
      left++
    }
  }
  return nums
}
Copy the code