0%

leetcode Wiggle Sort II

leetcode 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?

题目地址: leetcode Wiggle Sort II

题意:

给定一个数组,要求进行如下排序: 奇数的位置要大于两边。 如 nums[1] > nums[0]  ,nums[1] > nums[2]

思路:

方法一

排序,然后两边分别取,复杂度O(nlogn)

注意排完序之后应该倒着来。比如[4,5,5,6]这个 数据。

Java 7ms

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
public void wiggleSort(int[] nums) {
Arrays.sort(nums);
int[] temp = new int[nums.length];
int s = (nums.length + 1) >> 1, t = nums.length;
for (int i = 0; i < nums.length; i++) {
temp[i] = (i & 1) == 0 ? nums[--s] : nums[--t] ;
}

for (int i = 0; i < nums.length; i++)
nums[i] = temp[i];
}
}

Python 104ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
temp = sorted(nums)
s, t = (len(nums) + 1) >> 1, len(nums)
for i in xrange(len(nums)):
if i & 1 == 0:
s -= 1
nums[i] = temp[s]
else:
t -= 1
nums[i] = temp[t]

 

方法二

用快排的思想查找中位数,然后再合并两边。

最坏复杂度O(n^2),平均复杂度O(n)

Java 6ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class Solution {
public void wiggleSort(int[] nums) {
int medium = findMedium(nums, 0, nums.length - 1, (nums.length + 1) >> 1);
int s = 0, t = nums.length - 1 , mid_index = (nums.length + 1) >> 1;
int[] temp = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
if (nums[i] < medium)
temp[s++] = nums[i];
else if (nums[i] > medium)
temp[t--] = nums[i];
}

while (s < mid_index) temp[s++] = medium;
while (t >= mid_index) temp[t--] = medium;

t = nums.length;
for (int i = 0; i < nums.length; i++)
nums[i] = (i & 1) == 0 ? temp[--s] : temp[--t];
}

private int findMedium(int[] nums, int L, int R, int k) {
if (L >= R) return nums[R];
int i = partition(nums, L, R);
int cnt = i - L + 1;
if (cnt == k) return nums[i];
return cnt > k ? findMedium(nums, L, i - 1, k) : findMedium(nums, i + 1, R, k - cnt);
}

private int partition(int[] nums, int L, int R) {
int val = nums[L];
int i = L, j = R + 1;
while (true) {
while (++i < R && nums[i] < val) ;
while (--j > L && nums[j] > val) ;
if (i >= j) break;
swap(nums, i, j);
}
swap(nums, L, j);
return j;
}

private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}

 

本文是leetcode 324 Wiggle Sort II  的题解,更多题解可见

https://www.hrwhisper.me/leetcode-algorithm-solution/

请我喝杯咖啡吧~