LeetCode1.Two Sum(高效解法) C++

本文详细解析了一道经典算法题“两数之和”的解决方案,介绍了如何通过使用HashMap实现O(n)的时间复杂度来寻找数组中两个数的索引,使得这两个数相加等于给定的目标值。

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

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.

Example:

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

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

题目描述:

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数的索引。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

思路分析:

为了找到两个数索引,可以固定一个nums[i],然后再在数组中搜索(target-nums[i])的索引。

1. 暴力破解

两层遍历,固定一个元素,循环搜索另外一个元素,时间复杂度0(n^2),效率太低舍弃;

2. Hash map

由于对Hash表的搜索是0(1),所以我们可以先把数组元素全部放入Hash表(因为要求返回元素索引,所以让数组元素作键,数组元素索引作值)。这样只需一遍遍历数组元素即可,时间复杂度0(n)。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> vi;
        unordered_map<int,int> hmap;//声明一个hash map表
        for(auto i = 0; i < nums.size(); i++){
            hmap.insert(pair<int,int>(nums[i],i));
        }
        for(auto j = 0; j < nums.size(); j++){
            if(hmap.find(target - nums[j]) != hmap.end()){
                int k = hmap[target - nums[j]];
                if(k < j){
                    vi.push_back(k);
                    vi.push_back(j);  
                }
               
            }
        }
        return vi;
    }
};

参考

leetcode 1: 找出两个数相加等于给定数 two sum

点击打开链接



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值