Skip to content

Commit 4daba4c

Browse files
committed
feat: solved 324
1 parent 757626b commit 4daba4c

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.fghpdf.WiggleSortII;
2+
3+
import java.util.Arrays;
4+
import java.util.Comparator;
5+
6+
/**
7+
* @author fghpdf
8+
* @date 2019/12/29
9+
* https://leetcode.com/problems/wiggle-sort-ii/
10+
* 没懂。。。
11+
* https://leetcode.com/problems/wiggle-sort-ii/discuss/77682/Step-by-step-explanation-of-index-mapping-in-Java
12+
**/
13+
public class Solution {
14+
public void wiggleSort(int[] nums) {
15+
int median=findKthLargest(nums,(nums.length+1)/2);
16+
int odd=1;
17+
int even=nums.length%2==0?nums.length-2:nums.length-1;
18+
int[] tmpArr=new int[nums.length];
19+
for(int i=0;i<nums.length;i++){
20+
if(nums[i]>median){
21+
tmpArr[odd]=nums[i];
22+
odd+=2;
23+
continue;
24+
}
25+
if(nums[i]<median){
26+
tmpArr[even]=nums[i];
27+
even-=2;
28+
continue;
29+
}
30+
}
31+
while(odd<nums.length){
32+
tmpArr[odd]=median;
33+
odd+=2;
34+
}
35+
while(even>=0){
36+
tmpArr[even]=median;
37+
even-=2;
38+
}
39+
for(int i=0;i<nums.length;i++){
40+
nums[i]=tmpArr[i];
41+
}
42+
43+
44+
}
45+
46+
private int findKthLargest(int[] nums, int k) {
47+
int[] sorted = Arrays.stream(nums).boxed()
48+
.sorted(Comparator.reverseOrder())
49+
.mapToInt(Integer::intValue)
50+
.toArray();
51+
52+
return sorted[k - 1];
53+
}
54+
}

0 commit comments

Comments
 (0)