leetcode菜鸡斗智斗勇系列(8)--- Find N Unique Integers Sum up to Zero

1.原题:

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

 

2.解题思路:

这题的解法大致上有两种思路,一种是比较傻的办法就是从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; }
相关文章
相关标签/搜索