Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
题意
从一个数组中找到两个数,使这两个数之和等于给定的目标数。 返回这两个数在数组中的位置
思路
1.将原数组复制在temp中,并排序
2.从排序数组的头和尾开始扫描:如果head+tail<target,那么head++,接着扫描;
如果head+tail>target,那么tail--,接着扫描;直到head+tail=target。
3.从原数组中找到temp[head] 和 temp[tail]。
1 //Runtime: 16 ms 2 class Solution { 3 public: 4 vector<int> twoSum(vector<int>& nums, int target) { 5 vector<int> temp = nums; 6 sort(temp.begin(),temp.end()); 7 int head = 0; 8 int tail = temp.size()-1; 9 while(temp[head]+temp[tail] != target) 10 { 11 if(temp[head]+temp[tail] > target) 12 tail--; 13 else 14 head++; 15 } 16 vector<int> array(2,0); 17 for(int i=0;i<temp.size();i++) 18 { 19 if(nums[i] == temp[head] || nums[i] == temp[tail]) 20 if(array[0] == 0) 21 array[0] = i+1; 22 else 23 array[1] = i+1; 24 } 25 return array; 26 } 27 };
时间: 2024-08-06 03:15:08