Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.less

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.spa

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

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2blog

直接暴力法O(n*n)超时,所以需采用hashmap,这里采用map来存储数据并进行搜索,其实现为ci

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4        vector<int> res;
 5        map<int,int> tmp;
 6        for(int i=0;i<nums.size();i++)
 7        {
 8            if(!tmp.count(nums[i]))
 9                tmp.insert(pair<int,int>(nums[i],i+1));
10            if(tmp.count(target-nums[i]))
11            {
12                int n=tmp[target-nums[i]];
13                if(n<i+1)
14                {
15                    res.push_back(n);
16                    res.push_back(i+1);
17                    return res;
18                }
19            }
20        }
21        return res;
22     }
23 };

 

红黑树。get

相关文章
相关标签/搜索