leetCode算法题目之我解(1)Two Sum

4450阅读 0评论2015-04-09 风箫夜吟
分类:C/C++

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

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.

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

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


需要注意的地方,给定的vector中数值无序、正负数、0值、相同数值

点击(此处)折叠或打开

  1. vector<int> twoSum(vector<int> &numbers, int target) {
  2.     vector<int> result;
  3.     map<int, vector<int> > imap;
  4.     int pos1 = 0;
  5.     int pos2 = 0;
  6.     for(unsigned int i = 0; i < numbers.size(); i++)
  7.     {
  8.         map<int, vector<int> >::iterator it = imap.find(numbers[i]);
  9.         if(it != imap.end())
  10.         {
  11.             it->second.push_back(i);
  12.             //cout << "key: " << it->first << " value: " << it->second.size() << endl;
  13.         }
  14.         else
  15.         {
  16.             vector<int> ivec;
  17.             ivec.push_back(i);
  18.             imap.insert(make_pair<int, vector<int> >(numbers[i],ivec));
  19.         }
  20.     }
  21.     for(unsigned int i = 0; i < numbers.size(); i++)
  22.     {
  23.         int temp = target - numbers[i];
  24.         map<int, vector<int> >::iterator it = imap.find(temp);
  25.         if(it != imap.end())
  26.         {
  27.             if(temp == numbers[i] && it->second.size() >= 2)
  28.             {
  29.                 for(unsigned int j = 0; j < it->second.size(); j++)
  30.                 {
  31.                     result.push_back(it->second[j] + 1);
  32.                 }
  33.                 return result;
  34.             }
  35.             else if(it->first != numbers[i])
  36.             {
  37.                 pos1 = i + 1;
  38.                 pos2 = it->second[0] + 1;
  39.                 result.push_back(pos1);
  40.                 result.push_back(pos2);
  41.                 return result;
  42.             }
  43.         }
  44.     }
  45.     return result;
  46. }

上一篇:c++的拷贝构造函数
下一篇:leetCode算法题目之我解(2)Add Two Numbers