lintcode 容易题:Partition Array by Odd and Even 奇偶分割数组

本文介绍如何利用快速排序算法实现整数数组中奇数与偶数的高效分割,无需额外空间,通过双指针技巧在原数组上进行操作。

题目:

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

样例

给定 [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

转载于:https://www.cnblogs.com/theskulls/p/4872667.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值