题目来源
题目描述
题目解析
正负数以0为中心对称
c++
class Solution {
public:
vector<int> sumZero(int n) {
vector<int> res(n, 0);
for (int i = 0; i < n / 2; ++i) {
res[i] = (i + 1);
res[n - i - 1] = -(i + 1);
}
return res;
}
};
java
public static int[] sumZero(int n) {
int[] ans = new int[n];
int index = 0;
for (int i = 0; i < n / 2; i++){
ans[index++] = i + 1;
ans[index++] = -(i + 1);
}
// 如果是奇数的话,最中间的那个数字是0
return ans;
}