forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_667.java
70 lines (66 loc) · 2.36 KB
/
_667.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
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class _667 {
public static class Solutoin1 {
/**
* inspired by this post: https://leetcode.com/problems/beautiful-arrangement-ii/discuss/1154683/Short-and-Simple-Solution-or-Multiple-Approaches-Explained-with-Examples-! and implemented it on my own
*/
public int[] constructArray(int n, int k) {
List<Integer> list = new ArrayList<>();
int maxSoFar = 1;
list.add(1);
boolean plus = true;
while (k > 0) {
if (plus) {
plus = false;
int num = list.get(list.size() - 1) + k;
maxSoFar = Math.max(maxSoFar, num);
list.add(num);
} else {
plus = true;
list.add(list.get(list.size() - 1) - k);
}
k--;
}
for (int start = maxSoFar + 1; start <= n; start++) {
list.add(start);
}
int[] result = new int[n];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
}
public static class Solutoin2 {
/**
* This is a very smart solution:
* First, we can see that the max value k could reach is n-1 which
* comes from a sequence like this:
* when n = 8, k = 5, one possible sequence is:
* 1, 8, 2, 7, 3, 4, 5, 6
* absolute diffs are:
* 7, 6, 5, 4, 1, 1, 1
* so, there are total 5 distinct integers.
* <p>
* So, we can just form such a sequence by putting the first part first and
* decrement k along the way, when k becomes 1, we just put the rest numbers in order.
*/
public int[] constructArray(int n, int k) {
int[] result = new int[n];
int left = 1;
int right = n;
for (int i = 0; i < n && left <= right; i++) {
if (k > 1) {
result[i] = k-- % 2 != 0 ? left++ : right--;
} else {
result[i] = k % 2 != 0 ? left++ : right--;
}
}
return result;
}
}
}