Advertisement
rudolf222222

Untitled

Oct 7th, 2022
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. std::vector<int> twoSum(std::vector<int>& nums, int target) {
  6.   std::vector<int> two;
  7.   two.push_back(0);
  8.   two.push_back(0);
  9.   std::vector<int> copy = nums;
  10.   int first, right;
  11.   std::sort(copy.begin(), copy.end());
  12.   int l = 0, r = (int)copy.size() - 1;
  13.   while (l < r) {
  14.     if (copy[l] + copy[r] == target) {
  15.       first = copy[l], right = copy[r];
  16.       break;
  17.     } else if (copy[l] + copy[r] < target) {
  18.       ++l;
  19.     } else {
  20.       --r;
  21.     }
  22.   }
  23.   for (int i = 0; i < nums.size(); ++i) {
  24.     if (nums[i] == first) {
  25.       two[0] = i;
  26.     } else if (nums[i] == right) {
  27.       two[1] = i;
  28.     }
  29.   }
  30.   return two;
  31. }
  32. int main() {
  33.   std::vector<int> nums;
  34.   int elem, target;
  35.   while (std::cin.peek() != '\n') {
  36.     std::cin >> elem;
  37.     nums.push_back(elem);
  38.   }
  39.   std::cin >> target;
  40.   std::vector<int> answer = twoSum(nums, target);
  41.   std::cout << "[ " << answer[0] << "," << answer[1] << " ]";
  42.   return 0;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement