Find N Unique Integers Sum up to Zero
给一个数字n, 返回一个数组, 里面有n个数, 里面的数相加等于0. 这个就是观察一下奇偶规律.
class Solution {
public int[] sumZero(int n) {
int[] res = new int[n];
if(n % 2 == 0){ // if even, n = 4 1 -1 2 -2
int k = 0;
for(int i = 1; i <= n/2; i++){
res[k++] = i;
res[k++] = -i;
}
}
else {
int k = 0;
res[k] = 0;
for(int i = 1; i <= n/2; i++){
res[k++] = i;
res[k++] = -i;
}
}
return res;
}
}