[每日一题] 105. 两数之和(数组、map)

1. 题目来源

链接:两数之和
来源:LeetCode

2. 题目说明

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例1:

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

3. 题目解析

思路分析

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

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

4. 代码展示

// 时间复杂度:O(n)
// 空间复杂度:O(n)
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int,int> record;
        for(int i = 0 ; i < nums.size() ; i ++){
       
            int complement = target - nums[i];
            if(record.find(complement) != record.end()){
                int res[] = {i, record[complement]};
                return vector<int>(res, res + 2);
            }

            record[nums[i]] = i;
        }
    }
};
// 时间复杂度:O(n^2)
// 空间复杂度:O(1)
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> vt(2, 0);
        for (int i = 0; i < nums.size() - 1; ++i) {
            for (int j = i + 1; j < nums.size(); ++j) {
                if (nums[i] + nums[j] == target) {
                    vt[0] = i;
                    vt[1] = j;
                    break;
                }
            }
        }
        return vt;
    }
};
发布了209 篇原创文章 · 获赞 42 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/yl_puyu/article/details/104072857