1.Two Sum

本文介绍了一种利用哈希表解决LeetCode上经典问题“两数之和”的方法。通过创建哈希表存储数组元素及其索引,算法能在O(n)时间内找出两个数的索引,使它们相加等于目标值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Click here to try this problem on Leetcode

Problems with tag: Array
Problems with tag : Hash Table
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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.

思路:这道题目比较简单,直接建立Hash Table来解决就可以了。方法是,先建立一个nums数组的Hash Table;然后for-loop依次遍历每个元素,看是否能够在Hash Table中找到target - nums[i],如果能够找到,就返回itarget - nums[i]在Hash Table中对应的下标。

C++代码如下:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
    vector<int> res;
    unordered_map<int,int> map;

    for(int i = 0; i < nums.size(); i++){
        int gap = target - nums[i];
        if(map.find(gap) != map.end())
            res = {i, map[gap]};
        else
            map[nums[i]] = i;
    }
    return res;
    }
};

Time: O(n).
Space: O(n).
相关题目:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值