My construction use 7 as example


  • 1
    W

    Use 7 as an example, we can obtain some clue about the construction of the array.
    7, 1
    [1,2,3,4,5,6,7] => [1,1,1,1,1,1]

    7,2
    [1,7,6,5,4,3,2] => [6,1,1,1,1,1]

    7,3
    [1,7,2,3,4,5,6] => [6,5,1,1,1,1]

    7,4
    [1,7,2,6,5,4,3] => [6,5,4,1,1,1]

    7,5
    [1,7,2,6,3,4,5] => [6,5,4,3,1,1]

    7,6
    [1,7,2,6,3,5,4] => [6,5,4,3,2,1]

    Below is my code implementation

    class Solution {
        public int[] constructArray(int n, int k) {
            int[] res = new int[n];
            int i, j = 1, m = n, s;
            for(i = 0; i < k; i ++) {
                if(i % 2 == 0) {
                    res[i] = j;
                    j ++;
                }
                else {
                    res[i] = m;
                    m --;
                }
            }
            s = i;
            if(s % 2 == 1) {
                for(s = i; s < n; s ++) {
                    res[s] = j;
                    j ++;
                }
            }
            else {
                for(s = i; s < n; s ++) {
                    res[s] = m;
                    m --;
                }
            }
            return res;
        }
    }
    
    

Log in to reply
 

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