LeetCode Solutions
667. Beautiful Arrangement II
Time: $O(n)$ Space: $O(n)$
class Solution {
public:
vector<int> constructArray(int n, int k) {
vector<int> ans;
for (int i = 0; i < n - k; ++i)
ans.push_back(i + 1);
for (int i = 0; i < k; ++i)
if (i % 2 == 0)
ans.push_back(n - i / 2);
else
ans.push_back(n - k + (i + 1) / 2);
return ans;
}
};
class Solution {
public int[] constructArray(int n, int k) {
int[] ans = new int[n];
for (int i = 0; i < n - k; ++i)
ans[i] = i + 1;
for (int i = 0; i < k; ++i) {
if (i % 2 == 0)
ans[n - k + i] = n - i / 2;
else
ans[n - k + i] = n - k + (i + 1) / 2;
}
return ans;
}
}
class Solution:
def constructArray(self, n: int, k: int) -> List[int]:
ans = list(range(1, n - k + 1))
for i in range(k):
if i % 2 == 0:
ans.append(n - i // 2)
else:
ans.append(n - k + (i + 1) // 2)
return ans