Advertisement
Niloy007

Two Sum II - Input array is sorted

Mar 14th, 2021
878
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.70 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> twoSum(vector<int>& numbers, int target) {
  4.         int x;
  5.         int v;
  6.         int ans, i;
  7.         for (i = 0; i < numbers.size(); i++) {
  8.             x = numbers[i];
  9.             v = target - x;
  10.             if (binary_search(numbers.begin(), numbers.end(), v)) {
  11.                 ans = lower_bound(numbers.begin(), numbers.end(), v) - numbers.begin();
  12.                 if(ans == i) {
  13.                     continue;
  14.                 }
  15.                 break;
  16.             }
  17.            
  18.         }
  19.        
  20.         vector<int> res;
  21.         res.push_back(i + 1);
  22.         res.push_back(ans + 1);
  23.         sort(res.begin(), res.end());
  24.         return res;
  25.     }
  26. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement