15 Find N Unique Integers Sum up to Zero

2021-08-18 16:00:16 浏览数 (2)

题目

Given an integer n, return any array containing n unique integers such that they add up to 0.

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:

代码语言:javascript复制
1 <= n <= 1000

分析

题意:给定正整数n,按升序给出n个不相同的数,这些数的累加和为0; 分析:

代码语言:javascript复制
n = 1, [0]
n = 2, [-1, 1]
n = 3, [-2, 0, 2]
n = 4, [-3, -1, 1, 3]
n = 5, [-4, -2, 0, 2, 4]

A[i] = i * 2 - n   1

解答

代码语言:javascript复制
class Solution {
    public int[] sumZero(int n) {
        int[] A = new int[n];
        for(int i=0;i<n;i  )
            A[i] = i*2-n 1;
        return A;
    }
}

0 人点赞