zoukankan      html  css  js  c++  java
  • lintcode:Wiggle Sort

    Wiggle Sort

    Given an unsorted array nums, reorder it in-place such that

    nums[0] <= nums[1] >= nums[2] <= nums[3]....
     注意事项

    Please complete the problem in-place.

    样例

    Given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].

    解题

    竟然可以直接交换

    对i位置

    对奇数位需要是:A[i] >= A[i-1]  奇数位的数大于后一个的数,当是A[i] < A[i-1] 的时候交换

    对偶数位需要是:A[i] <=A[i-1] 偶数位的数小于后一个数,当是A[i] > A[i-1] 的时候交换

    对给的样例

    原始数组:[3,5,2,1,6,4]

    第一次:[3,5,2,1,6,4] 3<=5 不交换

    第二次:[3,5,2,1,6,4] 5>=2 不交换

    第三次:[3,5,1,2,6,4] 2>1 交换 小的换到前面不影响上一次的情况 1<=2

    第四次:[3,5,1,6,2,4] 2<6 交换, 大的换的前面不影响,6>=2

    第五次:[3,5,2,1,6,4] 2<=4 不需要交换

    public class Solution {
        /**
         * @param nums a list of integer
         * @return void
         */
        public void wiggleSort(int[] nums) {
            // Write your code here
            if(nums == null || nums.length == 0)
                return;
            int n = nums.length;
            for(int i = 1;i<n ; i++){
                if( (i%2==1 && nums[i] < nums[i-1] ) || (i%2==0 && nums[i] > nums[i-1])){
                    nums[i]^=nums[i-1];
                    nums[i-1]^=nums[i];
                    nums[i]^=nums[i-1];
                }
            }
        }
    }
  • 相关阅读:
    为什么建立视图
    Oracle constraints type 约束类型
    python 环境
    查看oracle 数据库的编码格式
    trigger
    闪回操作 flashback
    row_number()over(partiton by order by ) rank() over(partition by order by )
    lag() 偏移
    date
    配置ES中IK分词器远程词库
  • 原文地址:https://www.cnblogs.com/bbbblog/p/5348361.html
Copyright © 2011-2022 走看看