GuilinDev

Lc1304

05 August 2008

1304. Find N Unique Integers Sum up to Zero

给一个n,随便返回一个数组,使其里面有n个不同数字,并加起来为0

方法1. 两边同时找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
    public int[] sumZero(int n) {
        int[] result = new int[n];
        int num = 1;
        for(int i = 0;i < n / 2; i++) {
            result[i] = num;
            result[n - i - 1] = -num;
            num++;
        }
        // 如果中间还剩一个数
        if(n % 2 == 1) {
            result[n / 2] = 0;
        }
        return result;
    }
}

方法2, 找规律

如果

1
2
3
4
5
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]

可以看出,规律如下:

1
A[i] = i * 2 - n + 1
1
2
3
4
5
6
7
8
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;
    }
}