Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 vector<int> num=nums; 5 sort(num.begin(), num.end()); 6 int len = num.size(); 7 int left = 0; 8 int right = len - 1; 9 while (left < right) 10 { 11 if ((num[left] + num[right])>target) 12 right--; 13 else 14 if ((num[left] + num[right]) < target) 15 left++; 16 else 17 break; 18 } 19 vector<int> vet; 20 for(int i=0;i<len;i++) 21 { 22 if(nums[i]==num[left]||nums[i]==num[right]) 23 vet.push_back(i); 24 } 25 26 return vet; 27 } 28 };