首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >15 Find N Unique Integers Sum up to Zero

15 Find N Unique Integers Sum up to Zero

作者头像
devi
发布2021-08-18 16:00:16
发布2021-08-18 16:00:16
3130
举报
文章被收录于专栏:搬砖记录搬砖记录

题目

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;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/02/04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 分析
  • 解答
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档