Problem

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.

Solution

public class Solution {
    public void partitionArray(int[] nums) {
        int start = 0, end = nums.length - 1;
        while (start < end) {
            while (nums[start] % 2 != 0) start++;
            while (nums[end] % 2 == 0) end--;
            if (start < end) {
                int temp = nums[start];
                nums[start] = nums[end];
                nums[end] = temp;
            }
        }
        return;
    }
}

linspiration
161 声望53 粉丝

引用和评论

0 条评论