LeetCode //C - 1. Two Sum

1. Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:
  • 2 < = n u m s . l e n g t h < = 1 0 4 2 <= nums.length <= 10^4 2<=nums.length<=104
  • − 1 0 9 < = n u m s [ i ] < = 1 0 9 -10^9 <= nums[i] <= 10^9 −109<=nums[i]<=109
  • − 1 0 9 < = t a r g e t < = 1 0 9 -10^9 <= target <= 10^9 −109<=target<=109
  • Only one valid answer exists.

From: LeetCode

Link: 1. Two Sum


Solution:

Ideas:

In this implementation, we loop through each element and then loop through the rest of the elements to find a pair that sums up to the target. Once the pair is found, we store their indices in the result array and return it.

Code:
c 复制代码
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
    int* result = malloc(2 * sizeof(int));  // Allocate memory for the result
    *returnSize = 2;  // Set the return size to 2

    for (int i = 0; i < numsSize - 1; i++) {
        for (int j = i + 1; j < numsSize; j++) {
            if (nums[i] + nums[j] == target) {
                result[0] = i;
                result[1] = j;
                return result;
            }
        }
    }

    // In case no solution is found, though the problem statement guarantees one solution
    result[0] = -1;
    result[1] = -1;
    return result;
}
相关推荐
小青龙emmm26 分钟前
2025级C语言第四次周测题解
c语言·开发语言·算法
树在风中摇曳37 分钟前
【牛客排序题详解】归并排序 & 快速排序深度解析(含 C 语言完整实现)
c语言·开发语言·算法
minji...40 分钟前
算法---模拟/高精度/枚举
数据结构·c++·算法·高精度·模拟·枚举
执笔论英雄1 小时前
【大模型训练】forward_backward_func返回多个micro batch 损失
开发语言·算法·batch
序属秋秋秋3 小时前
《Linux系统编程之进程基础》【进程优先级】
linux·运维·c语言·c++·笔记·进程·优先级
草莓熊Lotso3 小时前
《算法闯关指南:优选算法--模拟》--41.Z 字形变换,42.外观数列
开发语言·c++·算法
啊吧怪不啊吧3 小时前
算法王冠上的明珠——动态规划之斐波那契数列问题
大数据·算法·动态规划
无敌最俊朗@10 小时前
力扣hot100-206反转链表
算法·leetcode·链表
Kuo-Teng10 小时前
LeetCode 279: Perfect Squares
java·数据结构·算法·leetcode·职场和发展
王哈哈^_^10 小时前
YOLO11实例分割训练任务——从构建数据集到训练的完整教程
人工智能·深度学习·算法·yolo·目标检测·机器学习·计算机视觉