LeetCode Wiggle Sort II

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
个人分类: 算法/oj
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

LeetCode Wiggle Sort II

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭