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:
/**
 * 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;
}

相关推荐

  1. nvm1.1.11

    2023-12-13 22:12:01       30 阅读
  2. 1.下午试题1

    2023-12-13 22:12:01       9 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-13 22:12:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-13 22:12:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-13 22:12:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-13 22:12:01       18 阅读

热门阅读

  1. 【编码器】位置管理器BoosterPack

    2023-12-13 22:12:01       37 阅读
  2. 重载和重写的区别

    2023-12-13 22:12:01       39 阅读
  3. ARM day8

    ARM day8

    2023-12-13 22:12:01      34 阅读
  4. lzma --- 用 LZMA 算法压缩

    2023-12-13 22:12:01       33 阅读
  5. SpringBoot登录校验-JWT令牌

    2023-12-13 22:12:01       38 阅读
  6. MySQL_9.B-数索引

    2023-12-13 22:12:01       31 阅读
  7. 微信网页授权步骤说明

    2023-12-13 22:12:01       86 阅读
  8. 【Python】函数的定义和函数的处理

    2023-12-13 22:12:01       36 阅读