【Leetcode】1. Two Sum 集合中找到两个元素之和等于给定值

1. 题目

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

2. 思路

建立hashmap,去查找余数是否存在。

3. 代码

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        _map.clear();
        int size = nums.size();
        for (int i = 0; i < size; i++) {
            int cur = nums[i];
            int need = target - cur;
            auto f = _map.find(need);
            if (f != _map.end()) {
                
                res.push_back(f->second + 1);
                res.push_back(i + 1);
                return res;
            }
            _map[cur] = i;
        }
        return res;
    }
private:
    unordered_map<int, int> _map;
};
    原文作者:knzeus
    原文地址: https://segmentfault.com/a/1190000007272540
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞