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 nums0 + nums1 == 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 <= numsi <= 10^9 −109<=numsi<=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;
}
相关推荐
xxwl5856 小时前
一个原创题(二)
c++·算法
moeyui7056 小时前
LeetCode 380:Insert Delete GetRandom O(1) 题解和一些延伸
算法·leetcode·职场和发展
三千里6 小时前
路径规划算法-备忘
算法·自动驾驶·动态规划
圣保罗的大教堂6 小时前
leetcode 3689. 最大子数组总值 I 中等
leetcode
退休倒计时7 小时前
【每日一题】LeetCode 15. 三数之和 TypeScript
数据结构·算法·leetcode·typescript
林爷万福7 小时前
MATLAB光谱数据分析从入门到项目实战
算法·光纤光谱仪
吴可可1237 小时前
AutoCAD2016二次开发环境配置指南
算法·机器学习
一条大祥脚7 小时前
ABC461 枚举|扫描线|动态前缀和|数论|dfs枚举子集
算法·深度优先
计算机安禾7 小时前
【数据库系统原理】第14篇:关系模式的语义约束:函数依赖的公理系统与闭包计算
人工智能·算法·机器学习
量化君也7 小时前
快速入门量化交易都要学些什么?
大数据·人工智能·python·算法·金融