Java O(n) Solution


  • 1
    public int[] constructArray(int n, int k) {
        int[] ret = new int[n];
        int hi = n;
        int lo = 2;
        ret[0] = 1;
        boolean last_hi = false;
        for (int i = 1; i < n; i++) {
            if (k > 1) {
                if (!last_hi){
                    ret[i] = hi;
                    hi --;
                }
                else {
                    ret[i] = lo;
                    lo ++;
                }
                last_hi = !last_hi;
                k--;
            }
            else {
                if (last_hi) {
                    ret[i] = hi;
                    hi--;
                }
                else {
                    ret[i] = lo;
                    lo++;
                }
            }
        }
        return ret;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.