Partition Array by Odd and Even

来源:互联网 发布:网页js代码 编辑:程序博客网 时间:2024/06/08 17:39

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[] arr) {        /* Initialize left and right indexes */        int left = 0, right = arr.length - 1;        while (left < right)        {            /* Increment left index while we see 0 at left */            while (arr[left]%2 == 0 && left < right)                left++;            /* Decrement right index while we see 1 at right */            while (arr[right]%2 == 1 && left < right)                right--;            if (left < right)            {                /* Swap arr[left] and arr[right]*/                int temp = arr[left];                arr[left] = arr[right];                arr[right] = temp;                left++;                right--;            }        }    }}
0 0
原创粉丝点击