找回密码
 立即注册
首页 业界区 安全 每天一个小算法:两数之和

每天一个小算法:两数之和

孩负范 2025-6-1 00:09:49
题目描述

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
<img >
  1. 给定 nums = [2, 7, 11, 15], target = 9
  2. 因为 nums[0] + nums[1] = 2 + 7 = 9
  3. 所以返回 [0, 1]
复制代码
题目解析

使用查找表来解决该问题。
设置一个 map 容器 record 用来记录元素的值与索引,然后遍历数组 nums。

  • 每次遍历时使用临时变量 complement 用来保存目标值与当前值的差值
  • 在此次遍历中查找 record ,查看是否有与 complement 一致的值,如果查找成功则返回查找值的索引值与当前变量的值 i
  • 如果未找到,则在 record 保存该元素与索引值 i
动画描述

1.gif

代码实现

C++

<img >
  1. // 1. Two Sum
  2. // https://leetcode.com/problems/two-sum/description/
  3. // 时间复杂度:O(n)
  4. // 空间复杂度:O(n)
  5. class Solution {
  6. public:
  7.     vector<int> twoSum(vector<int>& nums, int target) {
  8.         unordered_map<int,int> record;
  9.         for(int i = 0 ; i < nums.size() ; i ++){
  10.       
  11.             int complement = target - nums[i];
  12.             if(record.find(complement) != record.end()){
  13.                 int res[] = {i, record[complement]};
  14.                 return vector<int>(res, res + 2);
  15.             }
  16.             record[nums[i]] = i;
  17.         }
  18.         return {};
  19.     }
  20. };
复制代码
 
C

<img >
[code]// 1. Two Sum// https://leetcode.com/problems/two-sum/description/// 时间复杂度:O(n)// 空间复杂度:O(n)/** * Note: The returned array must be malloced, assume caller calls free(). */int* twoSum(int* nums, int numsSize, int target, int* returnSize){    int *ans=(int *)malloc(2 * sizeof(int));    int i,j;    bool flag=false;     for(i=0;i
您需要登录后才可以回帖 登录 | 立即注册