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

Difficulty: easy

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 second half.

Example:

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

Tip:

  1. 1 <= nums.length <= 50000
  2. 1 <= nums[i] <= 10000

Solution

Language: java

class Solution { public int[] exchange(int[] array) { int i = 0; int j = array.length - 1; while(i < j) { if(array[i] % 2 == 0 && array[j] % 2 ! = 0) { int tmp = array[i]; array[i] = array[j]; array[j] = tmp; i++; j--; } if(array[i] % 2 ! = 0) { i++; } if(array[j] % 2 == 0) { j--; } } return array; }}Copy the code