Partition Array by Odd and Even

LintCode-373.Partition Array by Odd and Even

Partition an integers array into odd number first and even number second.

Example: Given [1, 2, 3, 4], return [1, 3, 2, 4]

Challenge: Do it in-place.

public class Solution {
    /**
     * @param nums: an array of integers
     * @return: nothing
     */
    public void partitionArray(int[] nums) {
        if (nums == null || nums.length == 0) {
            return;
        }
        
        int i = 0, j = nums.length - 1;
        
        while (i < j) {
            while (i < j && nums[i] % 2 == 1) {
                i++;
            }
            
            while (i < j && nums[j] % 2 == 0) {
                j--;
            }
            
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
            i++;
            j--;
        }
    }
}

Hope this helps,
Michael

DigitalOcean Referral Badge