https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/ui
Given an integer n
, return any array containing n
unique integers such that they add up to 0.spa
翻譯:給你一個int數n,返回一個包含n個惟一的int的array,其和sum必須爲0.翻譯
Input: n = 5 code
Output: [-7,-1,1,3,4]leetcode
這題的解法大致上有兩種思路,一種是比較傻的辦法就是從0開始,向兩側擴散,好比說n=3,你的 output 就是 [-1,0,1].若是是n=5,就是[-2,-1,0,1,2]。get
def sumZero(self, n: int) -> List[int]: ans = [0] * n start, end = 0, n - 1 while start < end: ans[start], ans[end] = -end, end start, end = start + 1, end - 1 return ans
另外一種比較聰明,就是像這位大佬同樣:https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/discuss/465585/JavaC%2B%2BPython-Find-the-Ruleit
找到規則: A[i] = i * 2 - n + 1 , A[]就是指Output的這個array,舉個例子就說,n=3,你的結果能夠是 [-2,-1,0,1,2],那這個規則是符合的。io
vector<int> sumZero(int n) { vector<int> A(n); for (int i = 0; i < n; ++i) A[i] = i * 2 - n + 1; return A; }