zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    MySQL高可用之MHA的搭建
    MySQL MGR 集群搭建(单主模式&多主模式)
    ansible-playbook定义变量与使用
    linux LVM逻辑卷管理
    Oracle 19C RAC 静默(silent)安装on RHEL7.x
    Python语言基础02-变量和运算
    Python之路,Day6
    Python 之路 Day5
    Python之路,Day4
    Python之路,Day3
  • 原文地址:https://www.cnblogs.com/theskulls/p/4872667.html
Copyright © 2011-2022 走看看