Leetcode 667. Beautiful Arrangement II
Given two integers n
and k
, you need to construct a permutation of the integers from 1
to n
such that there are exactly k
distinct absolute differences between consecutive elements.
n
and k
satisfying 1 ≤ k
< n
?
n
be a large value like 10^6, and what is the expected complexity?
n
can be large, but an efficient solution is expected to handle this.k
distinct differences is acceptable?
k
distinct absolute differences exist.1
to n
.k
distinct differences.k
distinct differences, fill the remaining part of the permutation straightforwardly.Let’s implement this strategy in the code:
import java.util.*;
public class BeautifulArrangementII {
public int[] constructArray(int n, int k) {
int[] result = new int[n];
int left = 1, right = n;
boolean flag = true;
for (int i = 0; i < k; i++) {
if (flag) {
result[i] = left++;
} else {
result[i] = right--;
}
flag = !flag;
}
if (k % 2 == 0) {
for (int i = k; i < n; i++) {
result[i] = left++;
}
} else {
for (int i = k; i < n; i++) {
result[i] = right--;
}
}
return result;
}
public static void main(String[] args) {
BeautifulArrangementII solution = new BeautifulArrangementII();
System.out.println(Arrays.toString(solution.constructArray(3, 1))); // [1, 2, 3]
System.out.println(Arrays.toString(solution.constructArray(3, 2))); // [1, 3, 2] or [2, 1, 3] etc.
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?