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;
}
相关推荐
诸葛务农32 分钟前
光电对抗:多模/复合制导中算法和软件平台
算法
Starshime39 分钟前
【C语言】变量和常量
c语言·开发语言
晨非辰42 分钟前
#C语言——刷题攻略:牛客编程入门训练(十):攻克 循环控制(二),轻松拿捏!
c语言·开发语言·经验分享·学习·visual studio
Swift社区1 小时前
LeetCode 378 - 有序矩阵中第 K 小的元素
算法·leetcode·矩阵
墨染点香1 小时前
LeetCode 刷题【73. 矩阵置零】
算法·leetcode·矩阵
tqs_123451 小时前
redis zset score的计算
java·算法
_Coin_-1 小时前
算法训练营DAY60 第十一章:图论part11
算法·图论
林木辛1 小时前
LeetCode热题 438.找到字符中所有字母异位词 (滑动窗口)
算法·leetcode
和鲸社区1 小时前
四大经典案例,入门AI算法应用,含分类、回归与特征工程|2025人工智能实训季初阶赛
人工智能·python·深度学习·算法·机器学习·分类·回归