Simple C++ answer


  • 0
    D

    The range for k is: 0 < k < n

    We get k == 1 at:
    [1, 2, 3, 4, 5, ...]

    We get k == n - 1 at:
    [1, n, 2, n-1, 3, n-2, 4, n-3, ...]

    To get k unique numbers (according to the algorithm [|a1 - a2|, |a2- a3|, ...]), list k - n numbers in sequential order (from 1 to k - n) before alternating with the decreasing sequence [n, n-1, n-2, ...].

    Example:
    n = 5
    k = 3

    [1, 2, 5, 3, 4]

    or

    [1, 2, n, 3, n-1]

    class Solution {
    public:
        vector<int> constructArray(int n, int k) {
            vector<int> result;
            if (k < 1 || k > n - 1) {
                return result;
            }
            
            int start = 1;
            int end = n;
            for (int i = 0; i < n; i ++) {
                if (n - k == i) {
                    result.push_back(end--);
                    k -= 2;
                } else {
                    result.push_back(start++);
                }
            }
            
            return result;
        }
    };
    

Log in to reply
 

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