LeetCode-05-23

http://leetcode.com/onlinejudge#question_1

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int> &numbers, int target) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         
 7         vector<int> result;
 8         map<int, int> mymap;
 9         
10         typedef vector<int>::iterator iter_type;
11         typedef map<int, int>::iterator map_iter_type;
12 
13         map_iter_type map_iter;
14         for(iter_type it = numbers.begin(); it != numbers.end(); ++it) {
15             map_iter = mymap.find(target - *it);
16             if (mymap.end() != map_iter) {
17                 result.push_back(map_iter->second);
18                 result.push_back(it-numbers.begin()+1);
19                 return result;
20             }
21             mymap[*it] = it-numbers.begin()+1;
22         }
23         
24         /*
25         vector<int> result;
26         typedef vector<int>::iterator iter_type;
27         for(iter_type it1 = numbers.begin(); it1 != numbers.end(); ++it1) {
28             for(iter_type it2 = it1+1; it2 != numbers.end(); ++it2) {
29                 if(target == *it1 + *it2) {
30                     result.push_back(it1-numbers.begin()+1);
31                     result.push_back(it2-numbers.begin()+1);
32                     break;
33                 }
34             }        
35         }
36         
37         return result;
38         */
39     }
40 };
View Code

 

posted @ 2013-05-23 17:47  tangr206  阅读(190)  评论(0编辑  收藏  举报