其他分享
首页 > 其他分享> > 【剑指Offer 18】调整数组顺序使奇数位于偶数前面

【剑指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;
    }
}

标签:end,shu,nums,int,18,Offer,偶数,public
来源: https://www.cnblogs.com/liaozibo/p/offer-21.html