Java simple solution


  • 1
    O
    public int[] constructArray(int n, int k) {
        //number 1-n. if ascending order, always has diff = 1. 
        //reorder to be 1, k+1, 2, k, 3 ... so have diff = k,k-1,k-2....1
        int[] res = new int[n];
        int inc = 1, dec = k+1;
        for(int i=0;i<=k;i++){
            if(i%2==0)
                res[i] = inc++;
            else
                res[i] = dec--;
        }
       
        for(int i=k+1;i<n;i++){
            res[i] = i+1;
        }
        
        return res;
    }

Log in to reply
 

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