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).

  • 相关阅读:
    自己收集的一些伪元素/伪类
    ie9的placeholder不显示的解决办法(包含多个密码框)
    9.14上午
    9.13
    9.11笔记
    html基础英语单词
    选择器的分辨
    学习笔记
    RecyleView
    自定义view获取宽高
  • 原文地址:https://www.cnblogs.com/lyc94620/p/10718423.html
Copyright © 2011-2022 走看看