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;
}
相关推荐
McGrady-1758 小时前
拓扑导航 vs 几何导航的具体实现位置
算法
副露のmagic8 小时前
更弱智的算法学习 day24
python·学习·算法
颜酱8 小时前
前端必备动态规划的10道经典题目
前端·后端·算法
wen__xvn8 小时前
代码随想录算法训练营DAY10第五章 栈与队列part01
java·前端·算法
cpp_25019 小时前
P2708 硬币翻转
数据结构·c++·算法·题解·洛谷
程序猿阿伟10 小时前
《Python复杂结构静态分析秘籍:递归类型注解的深度实践指南》
java·数据结构·算法
bubiyoushang88810 小时前
LFM脉冲串信号的模糊函数
算法
踩坑记录10 小时前
leetcode hot100 11.盛最多水的容器 medium 双指针
算法·leetcode·职场和发展
圣保罗的大教堂10 小时前
leetcode 865. 具有所有最深节点的最小子树 中等
leetcode
MM_MS10 小时前
Halcon基础知识点及其算子用法
开发语言·人工智能·python·算法·计算机视觉·视觉检测