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;
}
相关推荐
QiZhang | UESTC8 分钟前
JAVA算法练习题day11
java·开发语言·python·算法·hot100
屁股割了还要学12 分钟前
【数据结构入门】排序算法(4)归并排序
c语言·数据结构·学习·算法·排序算法
Tisfy18 分钟前
LeetCode 0966.元音拼写检查器:三个哈希表实现
leetcode·字符串·散列表·题解·哈希表
SccTsAxR26 分钟前
[C语言]常见排序算法①
c语言·开发语言·经验分享·笔记·其他·排序算法
笑口常开xpr31 分钟前
Linux 库开发入门:静态库与动态库的 2 种构建方式 + 5 个编译差异 + 3 个加载技巧,新手速看
linux·c语言·动态库·静态库
努力学习的小廉32 分钟前
我爱学算法之—— 位运算(上)
c++·算法
ゞ 正在缓冲99%…1 小时前
leetcode35.搜索插入位置
java·算法·leetcode·二分查找
lifallen1 小时前
字节跳动Redis变种Abase:无主多写架构如何解决高可用难题
数据结构·redis·分布式·算法·缓存
feifeigo1231 小时前
星座SAR动目标检测(GMTI)
人工智能·算法·目标跟踪
WWZZ20251 小时前
视觉SLAM第10讲:后端2(滑动窗口与位子图优化)
c++·人工智能·后端·算法·ubuntu·机器人·自动驾驶