LeetCode1-Two Sum(C++)

Description

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].

AC代码
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> mp;
        for(int i=0; i<nums.size(); i++) {
            auto it = mp.find(target-nums[i]);
            if(it!=mp.end()) {
                return {it->second, i};
            }
            mp[nums[i]] = i; //程序实际上是从这里开始的,首先录入nums里的各个数,first是数值本身,second是下标
        }
        return {};
    }
};
测试代码
int main() {
    Solution s;
    vector<int> a1{2, 7, 11, 15};
    vector<int> res = s.twoSum(a1, 9);
    cout<<"Result: ";
    for(int i=0;i<res.size();i++) {
        cout<<res[i]<<" ";
    }
    cout<<endl;
}
总结

这一题可以使用暴力解法,就是直接遍历所有的两个数的组合,算出它们的和,一旦遇到target,立马return。
另外一种比较常见的做法,就是利用map(也即是Python里的字典),第一遍遍历把各个数录入到map中,接着,进行第二遍的遍历,每遇到一个数x, 就看一下target-x在不在map里,如果在的话,就直接return二者的下标(second的值)。上面的"AC代码"即采用这种解法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值