【剑指Offer 18】调整数组顺序使奇数位于偶数前面

/**
 * 剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
 * https://leetcode.cn/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/
 *
 * 思路:快排思想
 * */
public class Solution {
    public int[] exchange(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return nums;
        }
        int n = nums.length;
        int start = -1;
        int end = n;
        while (start < end) {
            while (nums[++start] % 2 != 0) if (start == n - 1) break;
            while (nums[--end] % 2 == 0) if (end == 0) break;
            if (start >= end) break;
            exch(nums, start, end);
        }
        return nums;
    }

    private void exch(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
posted @ 2022-06-26 21:47  廖子博  阅读(21)  评论(0编辑  收藏  举报