Leetcode 1304. Find N Unique Integers Sum up to Zero
Given an integer n
, return any array containing n
unique integers such that they add up to 0.
n
?
n
is a non-negative integer.n
be zero?
n
is zero, the output should be an empty array.n
is zero, return an empty array.n
such that the sum of the elements is zero.(-i, i)
for i
from 1
to n/2
. This ensures each pair sums to zero.n
is odd, include 0
in the array since including 0
does not change the sum.#include <vector>
std::vector<int> sumZero(int n) {
std::vector<int> result;
// Add pairs (-i, i) to the result vector
for(int i = 1; i <= n / 2; ++i) {
result.push_back(-i);
result.push_back(i);
}
// If n is odd, add 0 to the result vector
if(n % 2 == 1) {
result.push_back(0);
}
return result;
}
result
to store the integers.(-i, i)
from 1
to n/2
. Each pair sums up to zero.n
is odd, we add an additional 0
to ensure the total number of integers is n
and the sum is zero.1
to n/2
and possibly add one more element if n
is odd.n
integers in the result vector.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?