runnig

find two elements of an array that sum up to T

Jan 30th, 2013
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. // http://leetcode.com/onlinejudge#question_1
  2. /*
  3.  
  4. Given an array of integers, find two numbers such that they add up to a specific target number.
  5.  
  6. 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.
  7.  
  8. You may assume that each input would have exactly one solution.
  9.  
  10. Input: numbers={2, 7, 11, 15}, target=9
  11. Output: index1=1, index2=2
  12.  
  13. */
  14. class Solution {
  15. public:
  16.     vector<int> twoSum(vector<int> &A, int T) {
  17.         // Start typing your C/C++ solution below
  18.         // DO NOT write int main() function
  19.         vector<int> ret;
  20.         if(A.empty() ) { return ret; }
  21.        
  22.        
  23.         typedef std::pair<int,int> val_idx;
  24.         vector<val_idx> pair_vec;
  25.        
  26.         size_t i;
  27.         const size_t N = A.size();
  28.        
  29.         for(i=0; i < N; ++i)
  30.         {
  31.             pair_vec.push_back(
  32.                 std::make_pair(A[i], int(i+1)));
  33.         }
  34.        
  35.         std::sort(pair_vec.begin(), pair_vec.end());
  36.                
  37.         i = 0;
  38.         size_t j = N - 1;
  39.         while(i<j)
  40.         {
  41.             const val_idx & a0 = pair_vec[i];
  42.             const val_idx & a1 = pair_vec[j];
  43.            
  44.             int S = a0.first + a1.first;
  45.             if(T < S) { --j; }
  46.             else if(S < T) { ++i; }
  47.             else{ break; }
  48.         }
  49.        
  50.         int idx1 = pair_vec[i].second;
  51.         int idx2 = pair_vec[j].second;
  52.        
  53.         if(idx1 > idx2)
  54.         {
  55.             std::swap(idx1, idx2);                    
  56.         }
  57.         ret.push_back(idx1);
  58.         ret.push_back(idx2);
  59.         return ret;
  60.     }
  61. };
Advertisement
Add Comment
Please, Sign In to add comment