-
Notifications
You must be signed in to change notification settings - Fork 1
/
LeetCode-324-Wiggle-Sort-II.java
79 lines (58 loc) · 1.93 KB
/
LeetCode-324-Wiggle-Sort-II.java
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class Solution {
// My Solution. Wrong Answer
// public void wiggleSort(int[] nums) {
// // PriorityQueue<Integer> pq = new PriorityQueue<>();
// // for (int num : nums) {
// // pq.add(num);
// // }
// int[] temp = new int[nums.length];
// for (int i = 0; i < nums.length; i++) {
// temp[i] = nums[i];
// }
// Arrays.sort(temp);
// int i = 0, j = nums.length / 2, k = 0;;
// while (i < nums.length / 2 && j < nums.length) {
// nums[k++] = temp[i++];
// nums[k++] = temp[j++];
// }
// while (i < nums.length / 2) {
// nums[k++] = temp[i++];
// }
// while (j < nums.length) {
// nums[k++] = temp[j++];
// }
// }
/*
Split into half, and assign the value.
Even count of array:
[0, 1, 2, 3, 4]
i j
[0, 1, 2, 3, 4, 5]
i j
https://leetcode.jp/leetcode-324-wiggle-sort-ii-%E8%A7%A3%E9%A2%98%E6%80%9D%E8%B7%AF%E5%88%86%E6%9E%90/
*/
public void wiggleSort(int[] nums) {
int[] temp = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
temp[i] = nums[i];
}
Arrays.sort(temp);
int mid = nums.length / 2;
if (nums.length % 2 == 0) mid--;
int i = mid, j = nums.length - 1, k = 0;
while (i >= 0 && j > mid) {
nums[k++] = temp[i--];
nums[k++] = temp[j--];
}
while (i >= 0) {
nums[k++] = temp[i--];
}
while (j > mid) {
nums[k++] = temp[j--];
}
}
/*
https://leetcode.com/problems/wiggle-sort-ii/discuss/77677/O(n)%2BO(1)-after-median-Virtual-Indexing
Find the kth element
*/
}