现在的位置: 首页 > 综合 > 正文

two sum

2019年10月02日 ⁄ 综合 ⁄ 共 765字 ⁄ 字号 评论关闭

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

时间复杂度为O(n)

  1. class Solution {
  2. public:
  3. vector<int> twoSum(vector<int> &numbers, int target) {
  4. int len = numbers.size();
  5. assert(len >= 2);
  6. vector<int> ret(2,0);
  7. map<int, int> mapping;
  8. vector<long long> mul(len,0);
  9. for(int i=0; i<len; ++i)
  10. {
  11. mul[i] = (target - numbers[i]) * numbers[i];
  12. if(mapping[mul[i]] >0)
  13. {
  14. if(numbers[mapping[mul[i]] -1] + numbers[i] == target)
  15. {
  16. ret[0] = mapping[mul[i]];
  17. ret[1] = i+1;
  18. return ret;
  19. }
  20. }
  21. else
  22. {
  23. mapping[mul[i]] = i+1;
  24. }
  25. }
  26. }
  27. };

抱歉!评论已关闭.