1304: Find-N-Unique-Integers-Sum-up-to-Zero
Easy


table of contents

Simply add all integers between [-n/2, -1] and [1, n/2] into the ans array as they will always sum to 0.

Then, if n is odd, we have to add one more unique integer, 0, into the array, which will not affect the sum of the pre-existing integers. Finally, we can simply just return the ans array.

code

class Solution {
public:
    vector<int> sumZero(int n) {
        vector<int> ans;
        for (int i = -n/2; i <= -1; ++i) {
            ans.push_back(i);
        }
        if (n % 2 == 1) {
            ans.push_back(0);
        }
        for (int i = 1; i <= n/2; ++i) {
            ans.push_back(i);
        }
        return ans;
    }
};

complexity

time taken