LeeCode-Two Sum

4531 단어 code
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=9Output: 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 };

좋은 웹페이지 즐겨찾기