1304 Find N Unique Integers Sum up to Zero 和為零的N個(gè)唯一整數(shù)
Description:
Given an integer n, return any array containing n unique integers such that they add up to 0.
Example:
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
題目描述:
給你一個(gè)整數(shù) n,請你返回 任意 一個(gè)由 n 個(gè) 各不相同 的整數(shù)組成的數(shù)組,并且這 n 個(gè)數(shù)相加和為 0 。
示例 :
示例 1:
輸入:n = 5
輸出:[-7,-1,1,3,4]
解釋:這些數(shù)組也是正確的 [-5,-1,1,2,3],[-3,-1,2,-2,4]。
示例 2:
輸入:n = 3
輸出:[-1,0,1]
示例 3:
輸入:n = 1
輸出:[0]
提示:
1 <= n <= 1000
思路:
從 1 - n到 n - 1按照步長為 2加入到結(jié)果數(shù)組即可
時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(1)
代碼:
C++:
class Solution
{
public:
vector<int> sumZero(int n)
{
vector<int> result(n);
for (int num = 1 - n, i = 0; num < n; num += 2, i++) result[i] = num;
return result;
}
};
Java:
class Solution {
public int[] sumZero(int n) {
int result[] = new int[n];
for (int i = 0, num = 1 - n; i < n; i++, num += 2) result[i] = num;
return result;
}
}
Python:
class Solution:
def sumZero(self, n: int) -> List[int]:
return range(1 - n, n, 2)