/* * 280. Wiggle Sort * 2016-6-27 by Mingyang * Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... * 对于题目的理解要准确!就是奇数位上的数字要大于等于周边的,那么我只用看小于的情况就交换好了 */ public void wiggleSort(int[] nums) { for (int i = 0; i < nums.length; i++) if (i % 2 == 1) { if (nums[i - 1] > nums[i]) swap(nums, i); } else if (i != 0 && nums[i - 1] < nums[i]) swap(nums, i); } public void swap(int[] nums, int i) { int tmp = nums[i]; nums[i] = nums[i - 1]; nums[i - 1] = tmp; } // 下面是我拙劣的解法,不是in place的空间 public static void wiggleSort11(int[] nums) { int len = nums.length; if (nums == null || len == 0) return; List<Integer> list1 = new ArrayList<Integer>(); for (int i = 0; i < len; i++) { list1.add(nums[i]); } Collections.sort(list1); int start = 0; int end = list1.size() - 1; int count = 0; while (start < end) { nums[count++] = list1.get(start); nums[count++] = list1.get(end); start++; end--; } if (len % 2 != 0) { nums[count] = list1.get(start); } }