LeetCode //C - 1304. Find N Unique Integers Sum up to Zero

1304. 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.

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:
  • 1 <= n <= 1000

From: LeetCode

Link: 1304. Find N Unique Integers Sum up to Zero


Solution:

Ideas:

Pair each positive integer i with -i, and if n is odd, include 0.

Code:
c 复制代码
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* sumZero(int n, int* returnSize) {
    *returnSize = n;
    int *ans = (int *)malloc(n * sizeof(int));
    
    int idx = 0;
    for (int i = 1; i <= n / 2; i++) {
        ans[idx++] = i;
        ans[idx++] = -i;
    }
    
    if (n % 2 == 1)
        ans[idx] = 0;
    
    return ans;
}
相关推荐
贝壳69017 分钟前
一个2026年2月才上传的库,凭什么敢碰2009年就有人写烂的题目
算法
文丑颜不良啊41 分钟前
LeetCode2901~2920题目解析
java·leetcode
贝壳6901 小时前
同一道三亿位选型题,三个AI给了我三个答案,我把它们拉进同一台机器复跑
算法
文丑颜不良啊3 小时前
LeetCode2861~2880题目解析
java·leetcode
青少儿编程课堂3 小时前
蓝桥杯青少组图形化 + 全国青少年信息素养大赛 + 电子学会图形化考级:校园大富翁经营闯关解析
c++·python·算法·bfs·信息学竞赛
another heaven3 小时前
【C/C++ 第一次跨越(上):用 C++11/14 停止制造新的旧代码】
c语言·c++·制造
在所不辞兄4 小时前
为什么在新能源汽车电驱与热管理开发中,AI驱动的数字孪生和数据驱动仿真正在部分替代对物理台架与实车标定的依赖?
人工智能·深度学习·神经网络·算法·机器学习
I_belong_to_jesus14 小时前
C++关于分支预测的优化1
开发语言·c++·算法
another heaven21 小时前
【C/C++ Ranges 是零开销抽象吗?拆开管道、惰性求值和编译期膨胀】
c语言·开发语言·c++