Leetcode 324: Wiggle Sort II

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 324: Wiggle Sort II相关的知识,希望对你有一定的参考价值。

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].

Note:
You may assume all input has valid answer.

Follow Up:
Can you do it in O(n) time and/or in-place with O(1) extra space?

 

 1 public class Solution {
 2     public void WiggleSort(int[] nums) {
 3         Array.Sort(nums);
 4         
 5         var copy = new int[nums.Length];
 6         
 7         int half = (nums.Length + 1) / 2;
 8         
 9         for (int i = 0; i < half; i++)
10         {
11             copy[2 * i] = nums[half - 1 - i];
12             
13             if (2 * i + 1 < copy.Length) copy[2 * i + 1] = nums[copy.Length - 1 - i];
14         }
15                
16         /*
17         int n = nums.Length;
18         
19         
20         for (int i = m - 1, j = 0; i >= 0; i--, j += 2) copy[j] = nums[i];
21         for (int i = n - 1, j = 1; i >= m; i--, j += 2) copy[j] = nums[i];
22         */
23         
24         for (int i = 0; i < copy.Length; i++)
25         {
26             nums[i] = copy[i];
27         }
28     }
29 }

 





以上是关于Leetcode 324: Wiggle Sort II的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 324 Wiggle Sort 2

280. Wiggle Sort/324. Wiggle Sort II

java 324. Wiggle Sort II(#)。java

java 324. Wiggle Sort II(#)。java

java 324. Wiggle Sort II(#)。java

java 324. Wiggle Sort II(#)。java