Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- #include <iostream>
- #include <vector>
- std::vector<int> twoSum(std::vector<int>& nums, int target) {
- std::vector<int> two;
- two.push_back(0);
- two.push_back(0);
- std::vector<int> copy = nums;
- int first, right;
- std::sort(copy.begin(), copy.end());
- int l = 0, r = (int)copy.size() - 1;
- while (l < r) {
- if (copy[l] + copy[r] == target) {
- first = copy[l], right = copy[r];
- break;
- } else if (copy[l] + copy[r] < target) {
- ++l;
- } else {
- --r;
- }
- }
- for (int i = 0; i < nums.size(); ++i) {
- if (nums[i] == first) {
- two[0] = i;
- } else if (nums[i] == right) {
- two[1] = i;
- }
- }
- return two;
- }
- int main() {
- std::vector<int> nums;
- int elem, target;
- while (std::cin.peek() != '\n') {
- std::cin >> elem;
- nums.push_back(elem);
- }
- std::cin >> target;
- std::vector<int> answer = twoSum(nums, target);
- std::cout << "[ " << answer[0] << "," << answer[1] << " ]";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement