奇偶分割数组

来源:互联网 发布:java如何实现四舍五入 编辑:程序博客网 时间:2024/05/29 08:09

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

样例

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

public class Solution {    /**     * @param nums: an array of integers     * @return: nothing     */    public void partitionArray(int[] nums) {        // write your code here;        if(nums.length==0 || nums.length==1){            return;        }        int index1 = 0;        int index2 = nums.length-1;        while(index1<index2){            while(nums[index1]%2 != 0){                index1++;            }            while(nums[index2]%2 == 0){                index2--;            }            //注意交换前index1和index2前需要重新比较两者大小            if(index1<index2){                int temp = nums[index1];                nums[index1] = nums[index2];                nums[index2] = temp;            }            index1++;            index2--;        }    }}


0 0
原创粉丝点击