[LeetCode]1. Two Sum

本文介绍了解决LeetCode经典题目“两数之和”的高效算法。通过使用哈希表,可以在O(n)的时间复杂度内找到数组中两个数相加等于特定目标值的下标,适用于包含重复元素的无序数组。

[LeetCode]1. Two Sum

题目描述

这里写图片描述

思路

题目给出的数组包含重复元素,并且无序
考虑使用hash
初始化一个空的hash
遍历数组
对于每个数nums[i], 计算互补的数 target - nums[i]
在hash中查找这个互补的数,若不存在,则将nums[i]和i对应存入hash中
若存在,在保存到数组中,返回

代码

#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        unordered_map<int, int> m;
        for (int i = 0; i < nums.size(); ++i){
            if (m.count(target - nums[i])) {
                res.push_back(m[target - nums[i]]);
                res.push_back(i);
                break;
            }
            else {
                m[nums[i]] = i;
            }
        }
        return res;
    }
};

int main() {
    vector<int> nums = { 3, 3 }, res;
    int target = 6;
    Solution s;
    res = s.twoSum(nums, target);
    for (int p : res)
        cout << p << " ";
    cout << endl;
    system("pause");
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值