[Lintcode]Partition Array by Odd and Even

来源:互联网 发布:奔奔数码淘宝王奔宏 编辑:程序博客网 时间:2024/06/17 22:31

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) {        int posOdd = 0, posEven = nums.length - 1;        while(true) {            while(posOdd < nums.length && nums[posOdd] % 2 == 1) posOdd++;            while(posEven >= 0 && nums[posEven] % 2 == 0) posEven--;            if(posOdd >= posEven) return;            else {                int tmp = nums[posEven];                nums[posEven] = nums[posOdd];                nums[posOdd] = tmp;            }        }    }}


0 0
原创粉丝点击