Leetcode 667. Beautiful Arrangement II
Given two integers n
and k
, you need to construct a list which contains n
different positive integers ranging from 1
to n
and exactly k
different integers exist such that there are exactly k
distinct absolute differences between consecutive elements of the list.
Return the list. If there are multiple valid lists, you can return any of them.
n
be less than 0
?
n
is a positive integer by the constraints.n
and k
?
n
can be quite large (up to 10,000). k
is such that 1 <= k < n
.#include <vector>
#include <iostream>
#include <cmath>
std::vector<int> constructArray(int n, int k) {
std::vector<int> result;
int low = 1, high = n;
for (int i = 0; i <= k; ++i) {
if (i % 2 == 0) {
result.push_back(low++);
} else {
result.push_back(high--);
}
}
if (k % 2 == 0) {
for (int i = high; i >= low; --i) {
result.push_back(i);
}
} else {
for (int i = low; i <= high; ++i) {
result.push_back(i);
}
}
return result;
}
int main() {
int n = 10, k = 4;
std::vector<int> result = constructArray(n, k);
for (int num : result) {
std::cout << num << " ";
}
return 0;
}
low = 1
and high = n
.k+1
elements, alternate between picking the smallest available number (low
) and the largest available number (high
). This guarantees that we achieve k
unique differences.k
is odd or even, fill the remaining part of the array:
k
is odd, continue with the numbers in the increasing order.k
is even, continue with the numbers in the decreasing order.This strategy ensures that exactly k
unique differences are achieved because the alternating selections in the first part create diverse gaps that cannot repeat within the initial k+1
numbers.
n
, as we store all n
elements in the result vector.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?