1. Two Sum

来源:互联网 发布:电信网络制式有哪些 编辑:程序博客网 时间:2024/05/16 04:51

1.Question

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

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        unordered_map<int, int> map;        vector<int> res;        int size = nums.size();        for(int i = 0; i < size; i++)        {            if(map.find(nums[i]) != map.end())            {                res.push_back(map[nums[i]]);                res.push_back(i);                break;            }            else map[target - nums[i]] = i;        }        return res;    }};

3.Note

a. 这题可以暴力枚举,复杂度为O(n^2)。利用哈希表,可以降低时间复杂度,但是至于为什么,还是需要深入理解unordered_map的存储方式等知识。

0 0