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;
}
相关推荐
从小白到软工5 分钟前
4-3 项目-学生成绩管理系统(上)
c语言·开发语言·数据结构·经验分享·ai编程
悠仁さん8 分钟前
非类型模板参数的特化与偏特化
java·数据结构·算法
垆边人似月.11 分钟前
最优河堤加固(二分答案 + 前缀和)
算法
171320330计算机毕设编程31 分钟前
计算机毕业设计 基于Hadoop的新能源汽车发展前景分析 LW PPT
java·大数据·hadoop·python·算法·随机森林·线性回归
垆边人似月.1 小时前
幻兽防御战(贪心算法)
数据结构·算法
DongQiShanRen1 小时前
六根硬件映射(下):物理闭环五步法,抽一条已实装的看
大数据·jvm·人工智能·算法·rust·哈希算法·集成学习
Code_Solitude1 小时前
c语言:指针(3)+冒泡排序
java·c语言·算法
FPGA信号处理1 小时前
【模式识别】第四节课:支持向量机
算法·机器学习·支持向量机
碧海银沙音频科技研究院1 小时前
面向长尾音频分类的知识蒸馏研究
人工智能·算法·音视频
巴巴媛6661 小时前
【Debug1】程序死机,while(1)循环,怎么办?
c语言·笔记·stm32·嵌入式硬件·bug