Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://leetcode.com/onlinejudge#question_1
- /*
- 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
- */
- class Solution {
- public:
- vector<int> twoSum(vector<int> &A, int T) {
- // Start typing your C/C++ solution below
- // DO NOT write int main() function
- vector<int> ret;
- if(A.empty() ) { return ret; }
- typedef std::pair<int,int> val_idx;
- vector<val_idx> pair_vec;
- size_t i;
- const size_t N = A.size();
- for(i=0; i < N; ++i)
- {
- pair_vec.push_back(
- std::make_pair(A[i], int(i+1)));
- }
- std::sort(pair_vec.begin(), pair_vec.end());
- i = 0;
- size_t j = N - 1;
- while(i<j)
- {
- const val_idx & a0 = pair_vec[i];
- const val_idx & a1 = pair_vec[j];
- int S = a0.first + a1.first;
- if(T < S) { --j; }
- else if(S < T) { ++i; }
- else{ break; }
- }
- int idx1 = pair_vec[i].second;
- int idx2 = pair_vec[j].second;
- if(idx1 > idx2)
- {
- std::swap(idx1, idx2);
- }
- ret.push_back(idx1);
- ret.push_back(idx2);
- return ret;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment