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

    Wiggle Sort II

    Given an unsorted array nums, reorder it such that

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

    You may assume all input has valid answer.

    样例

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

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

    挑战

    Can you do it in O(n) time and/or in-place with O(1) extra space?

    解题

    参考链接

    先进行排序,然后从中位数mid开始

    mid放在第一个位置 len-1放在第二个位置

    mid-1放在第三个位置,len-2放在第四个位置

    一直进行下去。。。

    这样的思想就是让大数和小数交叉排列

    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;
            Arrays.sort(nums);// 排序
            int[] temp = new int[nums.length];
            int mid = nums.length%2==0?nums.length/2-1:nums.length/2;// 中间下标 
            int index = 0;
            for(int i=0;i<=mid;i++){
                temp[index] = nums[mid-i];
                if(index+1<nums.length)
                    temp[index+1] = nums[nums.length-i-1];
                    index = index+2;
                }
            for(int i=0;i<nums.length;i++){
                nums[i] = temp[i];
            }
        }
    }
  • 相关阅读:
    (Beta)Let's-Beta阶段展示博客
    (Beta)Let's-M2后分析报告
    (Beta)Let's-版本测试报告
    (Beta)Let's-版本发布说明
    团队作业Week14
    Daily Scrum 12.20
    Daily Scrum 12.19
    Daily Scrum 12.18
    Daily Scrum 12.17
    最后一次作业
  • 原文地址:https://www.cnblogs.com/theskulls/p/5348463.html
Copyright © 2011-2022 走看看