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].
#include<algorithm>class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> re;//存儲結果 vector<int> temp=nums;//存儲原來的輸出 int low=0,high=nums.size()-1; sort(nums.begin(),nums.end());//對原來輸出進行排序 while(nums[low]+nums[high]!=target)//求那兩個數的排序后位置 { if(nums[low]+nums[high]>target) high--; else low++; } low=nums[low];//求那兩個數的值 high=nums[high]; for(int t=0;t<nums.size();t++)//通過值來求原來的位置 if(temp[t]==low || temp[t]==high) re.push_back(t); return re; }};新聞熱點
疑難解答