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;
}
相关推荐
李永奉21 分钟前
C语言—数组和指针练习题合集(二)
c语言·开发语言
qiuyunoqy1 小时前
蓝桥杯算法之搜索章 - 4
算法
Swaggy T1 小时前
自动驾驶决策算法 —— 有限状态机 FSM
linux·人工智能·算法·机器学习·自动驾驶
草莓熊Lotso1 小时前
【C语言强化训练16天】--从基础到进阶的蜕变之旅:Day2
c语言·经验分享·笔记·其他
MATLAB代码顾问1 小时前
MATLAB实现遗传算法求解路网路由问题
开发语言·算法·matlab
啊阿狸不会拉杆1 小时前
《算法导论》第 21 章-用于不相交集合的数据结构
数据结构·c++·算法·随机森林
gmmi1 小时前
文件IO(1)
c语言
快去睡觉~1 小时前
力扣11:盛水最多的容器
算法·leetcode·职场和发展
楽码2 小时前
了解HMAC及实现步骤
后端·算法·微服务
CoovallyAIHub3 小时前
YOLOVision 2025 官宣日期!大会议程暗藏 YOLOv14 发布信号?
深度学习·算法·计算机视觉