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
思路一: 两个数字一正一反,相加和就是0,例如 1 和 -1,2 和 -2. 对参数 n 完全分类,只可能出现以下两种情况
- n 偶数
- n 奇数
对于偶数,只要增加对应配对的数字即可,对于奇数,只需要在偶数上面再加上 0 即可
public int[] sumZero(int n) {
int[] result = new int[n];
int mid = n >> 1;
int idx = 1;
int j = 0;
for (int i = 0; i < mid; i++) {
result[j++] = idx;
result[j++] = -(idx++);
}
if (n % 2 != 0) {
result[n - 1] = 0;
}
return result;
}
标签:1304,idx,int,Example,++,result,easy,Input,leetcode
From: https://www.cnblogs.com/iyiluo/p/16848962.html