【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.code

You may assume that each input would have exactly one solution.ci

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

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

2. 思路

創建hashmap,去查找餘數是否存在。hash

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;
};
相關文章
相關標籤/搜索