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;
}
相关推荐
烟烟Abandon20 分钟前
FFmpeg开发基础之 C 语言中的循环语句
c语言·ffmpeg
重生之小比特42 分钟前
【算法拾光】递归、搜索与回溯算法简介
算法·深度优先
夏日听雨眠1 小时前
数据结构( Floyd)
数据结构·算法
金榜题名萱1 小时前
蓝桥杯 - 妮妮的月饼工厂(二分)
c语言·数据结构·c++·算法·蓝桥杯·动态规划
小王C语言2 小时前
优选算法:队列+宽选(bfs)
数据结构·算法·宽度优先
AI殉道师3 小时前
合因科技三大临床试验数字化模块:EDC + RTSM(IWRS)+ ePRO,从入组到随访如何协同?
科技·算法·临床试验数字化
Shaoshing4 小时前
LeetCode100 76.最小覆盖字串
java·算法·leetcode
不知棋者4 小时前
蓝桥杯 2020 省赛 B 组既约分数:从暴力枚举到欧拉函数前缀和
c++·算法·职场和发展·蓝桥杯
烟烟Abandon4 小时前
FFmpeg开发基础之 C 语言中的指针(上篇)
c语言·ffmpeg
电科_银尘4 小时前
【大模型算法与工程 63】视觉语言模型:视觉编码器如何接入LLM
人工智能·算法·语言模型