zoukankan      html  css  js  c++  java
  • Partition Array by Odd and Even

    Partition an integers array into odd number first and even number second.
    
    Example
    Given [1, 2, 3, 4], return [1, 3, 2, 4]
    
    Challenge
    Do it in-place.

    将数组中的奇数和偶数分开,使用『两根指针』的方法最为自然,奇数在前,偶数在后,若不然则交换之。

    JAVA:

    public class Solution {
        /**
         * @param nums: an array of integers
         * @return: nothing
         */
        public void partitionArray(int[] nums) {
            if (nums == null) return;
    
            int left = 0, right = nums.length - 1;
            while (left < right) {
                // odd number
                while (left < right && nums[left] % 2 != 0) {
                    left++;
                }
                // even number
                while (left < right && nums[right] % 2 == 0) {
                    right--;
                }
                // swap
                if (left < right) {
                    int temp = nums[left];
                    nums[left] = nums[right];
                    nums[right] = temp;
                }
            }
        }
    }

    源码分析

    注意处理好边界即循环时保证left < right.

    复杂度分析

    遍历一次数组,时间复杂度为 O(n), 使用了两根指针,空间复杂度 O(1).

  • 相关阅读:
    Python3笔记029
    Python3笔记028
    Python3笔记027
    Python3笔记026
    Python3笔记025
    Python3笔记024
    find the oracle logs
    asm command
    网上看到的一个朋友写的不错收藏着.
    在IBM AIX上安装Oracle RAC ,很多人都在找的东东.....
  • 原文地址:https://www.cnblogs.com/lyc94620/p/10718423.html
Copyright © 2011-2022 走看看