1.原題:
https://leetcode.com/problems/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.
翻譯:給你一個int數n,回傳一個包含n個唯一的int的array,其和sum必須為0.
Input: n = 5
Output: [-7,-1,1,3,4]
2.解題思路:
這題的解法大體上有兩種思路,一種是比較傻的辦法就是從0開始,向兩側擴散,比如說n=3,你的 output 就是 [-1,0,1].如果是n=5,就是[-2,-1,0,1,2],
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-Rule
找到規則: A[i] = i * 2 - n + 1 , A[]就是指Output的這個array,舉個例子就說,n=3,你的結果可以是 [-2,-1,0,1,2],那這個規則是符合的,
vector<int> sumZero(int n) {
vector<int> A(n);
for (int i = 0; i < n; ++i)
A[i] = i * 2 - n + 1;
return A;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/41052.html
標籤:其他
