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

 

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int> &numbers, int target) {
 4         vector<int>::iterator it,jt;
 5         int index1,index2;
 6         vector<int> OutputIndex;
 7         vector<int>::size_type number_size=numbers.size();
 8         int Judge=0;
 9         for(index1=1,it=numbers.begin()-1;it<numbers.end()-1;index1++,it++)
10         {
11             for(index2=1+index1,jt=numbers.begin();jt<numbers.end()-1;index2++,jt++)
12                 {
13                     if((*jt+*it)==target)
14                     {
15                         Judge=1;
16                         break;
17                     }
18                 }
19                 
20                 if(Judge==1)
21                     break;
22                 
23         }
24         OutputIndex.push_back(index1);
25         OutputIndex.push_back(index2);
26         
27         return OutputIndex;
28     }
29 };

 

相关文章:

  • 2021-06-25
猜你喜欢
  • 2022-01-28
  • 2022-03-10
  • 2021-11-21
  • 2022-12-23
  • 2022-02-13
  • 2021-07-17
  • 2021-12-06
相关资源
相似解决方案