【LeetCode刷题】1304. 和为零的N个唯一整数

给你一个整数 n,请你返回 任意 一个由 n 个 各不相同 的整数组成的数组,并且这 n 个数相加和为 0 。

示例 1:

输入:n = 5

输出:[-7,-1,1,3,4]

解释:这些数组也是正确的 [-5,-1,1,2,3],[-3,-1,2,-2,4]。

示例 2:

输入:n = 3

输出:[-1,0,1]

示例 3:

输入:n = 1

输出:[0]

=========================================================================================================================================================================================================================================================================================================================================

分析:

题目给了两个提示

1、Return an array where the values are symmetric. (+x , -x).

2、If n is odd, append value 0 in your returned array.

那就按x和-x赋值即可。

class Solution {
    public int[] sumZero(int n) {
        int[] res = new int[n];

        for(int i=0;i<n/2;i++){
            res[i] = i+1;
            res[i+n/2]= -(i+1);
        }
        return res;
    }
}

 看到另一种解法

class Solution {
    public int[] sumZero(int n) {
        int[] res = new int[n];
        int index = 0;
        for(int i=1;i<=n/2;i++){
            res[index++] = i;
            res[index++] = -i;
        }
        return res;
    }
}

参考:

1、https://leetcode-cn.com/problems/find-n-unique-integers-sum-up-to-zero/

2、https://leetcode-cn.com/problems/find-n-unique-integers-sum-up-to-zero/solution/java-zheng-fu-shu-yi-0wei-zhong-xin-dui-cheng-by-n/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值