题目
- 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数在数组的前半部分,所有偶数在数组的后半部分。
- leetcode链接:https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/
思路
- 双指针
/**
* @param {number[]} nums
* @return {number[]}
*/
var exchange = function (nums) {
let i = 0
let j = nums.length - 1
while (i < j) {
while (i < nums.length && !isOu(nums[i])) { i++ }
while (j >= 0 && isOu(nums[j])) { j-- }
if (i < j) swap(nums, i, j)
}
return nums
}
function isOu(num) {
return num % 2 === 0
}
function swap(arr, i, j) {
const temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}