首页 > 其他 > 详细

Leetcode 1. Two Sum(hash+stl)

时间:2019-08-22 22:51:14      阅读:90      评论:0      收藏:0      [点我收藏+]

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



 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         vector<int> tm;
 5         int a = 0, b = 0;
 6         int len = nums.size();
 7         
 8         multimap<int,int> hash;
 9         
10         for(int i = 0; i < len; i++){
11             hash.insert(pair<int,int>(nums[i],i));
12         }
13         for(int i = 0; i < len; i++){
14             multimap<int,int>::iterator s;
15             s=hash.find(target-nums[i]);
16             if(s== hash.end()){
17                 continue;
18             }
19             if(i != (*s).second){
20                 a = i;
21                 b = (*s).second;
22                 break;
23             }
24         }
25         tm.push_back(a);
26         tm.push_back(b);
27         return tm;
28     }
29 };

 

Leetcode 1. Two Sum(hash+stl)

原文:https://www.cnblogs.com/shanyr/p/11397099.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!