题目
给定一个无序的数组 nums,将它重新排列成 nums[0] < nums[1] > nums[2] < nums[3]… 的顺序。
示例 1:
输入: nums = [1, 5, 1, 1, 6, 4]
输出: 一个可能的答案是 [1, 4, 1, 5, 1, 6]
示例 2:
输入: nums = [1, 3, 2, 2, 3, 1]
输出: 一个可能的答案是 [2, 3, 1, 3, 1, 2]
说明:
你可以假设所有输入都会得到有效的结果。
进阶:
你能用 O(n) 时间复杂度和 / 或原地 O(1) 额外空间来实现吗?
解题思路
1、将数组进行升序排序
2、将数组从大到小开始隔位插入新数组进行排列, 代码中有详细注释和举例。
3、将排列好的新数组赋给原数组
4、原数组排列完毕
//java代码
public static void wiggleSort(int[] nums) {//举例 nums{4,3,2,1,5,6}
Arrays.sort(nums);//对数组进行排序 举例 nums{1,2,3,4,5,6}
int[] newnums = new int[nums.length];//定义新数组将原数组隔位插入
for (int i = nums.length - 1, j = 1; i >= 0 && j < nums.length ; i--, j = j + 2) {
//将数组从大到小开始从newnums[1]隔行插入进新数组,偶数数组到nums.length-1结束,奇数数组到nums.length-1-1处结束。
//举例 newnums{0,6,0,5,0,4}j的值分别为 1,3,5
newnums[j] = nums[i]; }
//继续将数组从大到小开始从newnums[0]隔行插入进新数组,偶数数组到nums.length-1-1结束,奇数数组到nums.length-1处结束。保证数组中每个位置都有值。
//举例 newnums{3,6,2,5,1,4}j的值分别为 0,2,4
for (int i = (nums.length - 1) / 2, j = 0; i >= 0 && j < nums.length; i--, j = j + 2) {
newnums[j] = nums[i]; }
//将排列好的数组数据赋给原数组
for (int i = 0; i < nums.length; i++) {
nums[i] = newnums[i];
}
}