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

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; }

 

猜你喜欢

转载自www.cnblogs.com/cptCarlvon/p/12131400.html