667. 优美的排列 II

approach 1

class Solution {
    public int[] constructArray(int n, int k) {
        int[] res = new int[n];
        int head = 0;
        int tail = (k+1) % 2 == 0 ? k : (k-1);
        for (int i = 1; i <= n; i++) {
            if (i <= k+1) {
                if (head <= k) {
                    res[head] = i;
                    head += 2;
                } else if (tail >= 1) {
                    res[tail] = i;
                    tail -= 2;
                }
            } else {
                res[i-1] = i;
            }
        }
        return res;
    }
}
Last Updated:
Contributors: jesse