Skip to content

667. Beautiful Arrangement II 👎

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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