LeetCode Wiggle Sort II

原创 2016年01月07日 06:55:13

Description:

Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....

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


Solution:

排序,然后分为[0, (n-1)/2]和[(n-1)/2 + 1, n-1]两个部分,将两个部分倒叙依次插入数组,即为所求


<span style="font-size:18px;">import java.util.*;

public class Solution {
	public void wiggleSort(int[] nums) {
		if (nums == null)
			return;

		int n = nums.length;
		int left = n;
		int mid = (n - 1) / 2 + 1;

		Arrays.sort(nums);
		int neoNums[] = new int[n];

		for (int i = 0; i < n; i++)
			neoNums[i] = (i & 1) == 0 ? nums[--mid] : nums[--left];

		for (int i = 0; i < n; i++)
			nums[i] = neoNums[i];

		return;
	}

	public static void main(String[] args) {
		int arr[] = { 0, 1, 2, 3, 4 };
		Solution s = new Solution();
		s.wiggleSort(arr);
	}
}</span>


相关文章推荐

LeetCode 324. Wiggle Sort II(摇摆排序)

原题网址:https://leetcode.com/problems/wiggle-sort-ii/ Given an unsorted array nums, reorder it such t...
  • jmspan
  • jmspan
  • 2016年04月26日 04:48
  • 803

[LeetCode 324] Wiggle Sort II

Given an unsorted array nums, reorder it such that nums[0] nums[2] . Example: (1) Given nums = [1...
  • sbitswc
  • sbitswc
  • 2016年01月13日 17:18
  • 2242

[leetcode] 324. Wiggle Sort II 解题报告

题目链接:https://leetcode.com/problems/wiggle-sort-ii/ Given an unsorted array nums, reorder it such t...

324. Wiggle Sort II 摆动排序

Given an unsorted array nums, reorder it such that nums[0] nums[2] . Example: (1) Given nums ...

[leetcode] - 324. Wiggle Sort II

题意大致为将给定数组中的元素按形如nums[0] < nums[1] > nums[2] < nums[3]….这种样子排列,顺序没要求。这道题O(1)时间复杂度和空间复杂度的最优解暂时没想出来,用蠢...

[leetcode] 280. Wiggle Sort 解题报告

题目链接: https://leetcode.com/problems/wiggle-sort/ Given an unsorted array nums, reorder it in-place...

LeetCode 280. Wiggle Sort(摇摆排序)

原题网址:https://leetcode.com/problems/wiggle-sort/ Given an unsorted array nums, reorder it in-pla...
  • jmspan
  • jmspan
  • 2016年04月14日 07:27
  • 550

[LeetCode]324. Wiggle Sort II

Problem DescriptionGiven an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < ...

LeetCode 324. Wiggle Sort II

思路首先仿照快速排序找出数组的中位数mid,这里平均复杂度O(n),最坏复杂度O(n^2)。 对数组下标作映射(假设数组长度为6):0 => 1 1 => 3 2 => 5 3 => 0 4 => ...

leetcode324~Wiggle Sort II

Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]…. Example...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode Wiggle Sort II
举报原因:
原因补充:

(最多只允许输入30个字)