Easy to Understand Java Solution


  • 0
    class Solution {
        public int[] constructArray(int n, int k) {
            if (n <= 0 || k <= 0 || k > n - 1) return new int[0];
            int count = 0;
            int[] res = new int[n];
            res[0] = 1;
            int head = 2, tail = n;
            int index = 1;
            int last = 1; // 1: head; -1: tail;
            while (head <= tail) {
                if (count == k - 1) break;
                res[index++] = tail--;
                last *= -1;
                count++;
    
                if (head > tail) break;
                if (count == k - 1) break;
                res[index++] = head++;
                last *= -1;
                count++;
                
            }
            if (count == k - 1) {
                if (last == 1) { // increasing order
                    for (int i = head; i <= tail; i++) {
                        res[index++] = i;
                    }
                } else { // decreasing order
                    for (int i = tail; i >= head; i--) {
                        res[index++] = i;
                    }
                }
            }
            return res;
        }
    }
    

Log in to reply
 

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