LeetCode --- Two Sum

4749 ワード

タイトルリンク
コードを添付:
 1 #include <vector>

 2 #include <iostream>

 3 #include <algorithm>

 4 using namespace std;  5 

 6 class Solution {  7 public:  8     vector<int> twoSum(vector<int> &numbers, int target) {  9         typedef pair<int, int> pii; 10         vector<pii> my_pair; 11         for (unsigned int i = 0; i < numbers.size(); i++) { 12             my_pair.push_back(pii(numbers[i], i+1)); 13  } 14  sort(my_pair.begin(), my_pair.end()); 15         vector <int> ans; 16         unsigned int beg = 0, end = numbers.size() - 1; 17         while (beg < end) { 18             if (my_pair[beg].first + my_pair[end].first == target) { 19  ans.push_back(my_pair[beg].second); 20  ans.push_back(my_pair[end].second); 21                 break; 22  } 23             else if (my_pair[beg].first + my_pair[end].first > target) { 24                 end--; 25  } 26             else if (my_pair[beg].first + my_pair[end].first < target) { 27                 beg++; 28  } 29  } 30          if (ans[0] > ans[1]) 31             swap(ans[0], ans[1]); 32          return ans; 33  } 34 };