1. Two Sum。

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


这道题是让在一个数组中找到两个相加能够与给定目标数相等的下标。可以是用map结构,然后遍历数组中的元素,拿到数值之后将其作为key在map中查找。如果在map中没有找到这个数值,则将目标数减去这个数值得到的结果作为key,这个数值的下标作为value存放在map中,然后继续往后面遍历。如果遇到了另一个数正好等于目标数减去刚才那个数,那么这个数作为key在map中就会存在。比如:目标数为3,数组第一个数为1,那么存放在map中的元素就是<2,0>,然后第二个数为2,此时发现map中已经有了<2,0>那么当前的下标和map中的下标就是我们所要求的结果。

#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> ret;
        unordered_map<int,int> m;
        if (!nums.empty()) {
            int i;
            for (i = 0; i < nums.size(); i++) {
                if (m.find(nums[i]) == m.end()) {//此时map中不存在此hash
                    m[target-nums[i]] = i;
                } else {
                    ret.push_back(m[nums[i]]);//另一个的下标索引
                    ret.push_back(i);//此时的下标索引
                    return ret;
                }
            }
        }
        return ret;
    }
};

int main() {
    Solution s;
    vector<int> num;
    num.push_back(2);
    num.push_back(7);
    num.push_back(11);
    num.push_back(15);
    vector<int> ret = s.twoSum(num,9);
    cout << ret[0] << " " << ret[1];
}

运行结果可能有误差。

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值