lintcode:Wiggle Sort II
2016-04-02 22:23
375 查看
Wiggle Sort II
Given an unsorted arraynums, 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]; } } }
相关文章推荐
- 【java集合框架源码剖析系列】java源码剖析之HashMap
- eSpeak: Linux文本转语音工具
- Linux优化-Preempt RT关键点
- Android常见问题集锦
- GitHub 上排名前 100 的 Android 开源库介绍
- Android应用自动更新功能的代码实现
- Python Thread
- 【java集合框架源码剖析系列】java源码剖析之HashMap
- leetcode 19.Remove Nth Node From End of List
- wamp虚拟主机配置
- [转] Mac OX上安装MongoDb
- uva 401.Palindromes
- 当tableview/scrollview滚动时定时器NSTimer / CADisplayLink停止响应问题
- 推荐一个GitHub上的软件工程师的面试题库
- 如何获取Activity的实例
- 20160402_C++中的内存对齐
- C++test临时缓存文件位置 — Windows
- HDU1159 && POJ1458:Common Subsequence(LCS)
- 程序员面试宝典
- C# Chart详细解析