Chinaunix首页 | 论坛 | 博客
  • 博客访问: 613897
  • 博文数量: 79
  • 博客积分: 848
  • 博客等级: 军士长
  • 技术积分: 1800
  • 用 户 组: 普通用户
  • 注册时间: 2012-06-26 19:30
文章分类

全部博文(79)

文章存档

2015年(4)

2013年(39)

2012年(36)

分类: C/C++

2015-04-09 14:37:53

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

阅读(4363) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~