题目:

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

样例

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

挑战

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

解题:

一次快速排序就可以得到结果

Java程序:

public class Solution {
    /**
     * @param nums: an array of integers
     * @return: nothing
     */
    public void partitionArray(int[] nums) {
        // write your code here;
        int left = 0;
        int right = nums.length - 1;
        quick(nums,left,right);
    }
    public void quick(int[] nums,int left,int right){
        int i=left;
        int j=right;
        if(i>=j)
            return;
        while(i<j){
            int tmp = nums[i];
            while(i<j && nums[j]%2==0) j--;
            if(i<j){
                nums[i++] = nums[j];
            }
            while(i<j &&nums[i]%2==1) i++;
            if(i<j){
                nums[j--] = nums[i];
            }
            nums[i] = tmp;
        }
    }
}
View Code

Python程序:

class Solution:
    # @param nums: a list of integers
    # @return: nothing
    def partitionArray(self, nums):
        # write your code here
        left = 0 
        right = len(nums) - 1
        while left<right:
            tmp = nums[left]
            while left<right and nums[right]%2==0:
                right-=1
            if left<right:
                nums[left] = nums[right]
                left +=1
            while left<right and nums[left]%2==1:
                left+=1
            if left<right:
                nums[right] = nums[left]
                right-=1
            nums[left] = tmp
View Code

总耗时: 408 ms