Two Sum

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

给定一个整数数组,返回两个数字的索引,使它们相加到特定目标。

您可以假设每个输入只有一个解决方案,并且您可能不会两次使用相同的元素。

在这里插入图片描述

2,题目思路

对于这道题,是比较特殊的一道题,它是LeetCode上的第一道题,应该也是做得人最多的一道题了,足足有380万个submission,fucking crazy!

一个比较常见的思路,是直接进行穷举,这样虽然可行,但是时间复杂度会达到O(n2),非常的不好。

对题目进行观察我们可以得知,题目是找出数组中的两个数,使得他们之和为给定的值。于是,思路便是,我们可以在遍历数组的过程中,判断 target - nums[i] 是否在我们所定义的容器中,如果在,就说明我们找到了对应的组合。此时直接break即可。
如果不在,则将该数字加入到我们的容器中,继续进行下一次的遍历。

对于这点,因为其中涉及到数字的值以及其对应的索引,同时我们更关注与查找到这个数字而非得到一个有序序列,因此,为了提高查找效率,我们使用unordered_map来作为我们的容器。

3,代码实现

int x = []() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        if(nums.size() == 0)
            return {};
        unordered_map<int,int> hashMap = {};
        vector<int> res = {};
        for(int i = 0;i<nums.size();i++){
            if(hashMap.find(target - nums[i])!=hashMap.end()){
                res.push_back(hashMap[target-nums[i]]);
                res.push_back(i);
                break;
            }
            else
                hashMap[nums[i]] = i;
        }
        return res;
    }
};
  • python解法
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        res = []
        # 构造一个字典,其中key为对应的数字的值,便于快速定位;value则为index,方便找到对应值在nums中的位置
        hash_map_dict = {}
        for index, value in enumerate(nums):
            another_number = target - value
            if another_number in hash_map_dict:
                return [index, hash_map_dict[another_number]]
            hash_map_dict[value] = index
        return []
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值