# 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`.

Example 1:

``````Input: n = 5
Output: [-7,-1,1,3,4]
Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].
``````

Example 2:

``````Input: n = 3
Output: [-1,0,1]
``````

Example 3:

``````Input: n = 1
Output: [0]
``````

Constraints:

• `1 <= n <= 1000`

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

``````class Solution {
public:
vector<int> sumZero(int n) {
vector<int> res(n);
int left = 0, right = n - 1, start = 1;
while (left < right) {
res[left++] = start;
res[right--] = -start;
++start;
}
return res;
}
};
``````

``````class Solution {
public:
vector<int> sumZero(int n) {
vector<int> res(n);
for (int i = 1; i < n; ++i) {
res[i] = i;
res[0] -= i;
}
return res;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1304

https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/

https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/discuss/463890/Simple-Java-%3A-Fill-from-both-sides

https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/discuss/465585/JavaC%2B%2BPython-Find-the-Rule

LeetCode All in One 题目讲解汇总(持续更新中…)

（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，快快加入吧～）

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation