373.Partition Array by Odd and Even-奇偶分割数组(容易题)

来源:互联网 发布:拳皇2002um键盘优化 编辑:程序博客网 时间:2024/06/02 07:08

奇偶分割数组

  1. 题目

    分割一个整数数组,使得奇数在前偶数在后。

  2. 样例

    给定 [1, 2, 3, 4],返回 [1, 3, 2, 4]。

  3. 挑战

    在原数组中完成,不使用额外空间。

  4. 题解

首尾双指针遍历,start指针查找偶数,end指针查找奇数,然后进行交换。

public class Solution {    /**     * @param nums: an array of integers     * @return: nothing     */    public void partitionArray(int[] nums) {        int start = 0;        int end = nums.length-1;        while (start < end)        {            while ((nums[start] & 1) == 1)            {                start++;            }            while ((nums[end] & 1) == 0)            {                end--;            }            if(start < end)            {                nums[start]=nums[start]+nums[end];                nums[end]=nums[start]-nums[end];                nums[start]=nums[start]-nums[end];            }        }    }}

Last Update 2016.9.13

0 0
原创粉丝点击