Q4: Two Sum
问题描述:
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
解决原理:
数组以升序排序
从数组S头、尾同时遍历数组,i为头端索引,j为尾端索引
若S[i]+S[j]=target,则返回对应索引
若S[i]+S[j]>target,则j--
否则i++
代码:
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int> &numbers, int target) { 4 int i = 0; 5 int j = numbers.size()-1; 6 int sum; 7 vector<int> rs; 8 vector<int> tmp; 9 10 for(int k = 0; k < numbers.size(); k++) 11 tmp.push_back(numbers[k]); 12 13 sort(tmp.begin(), tmp.end()); 14 while(i < j){ 15 sum = tmp[i] + tmp[j]; 16 if(sum == target){ 17 int m = 0; 18 while(numbers[m] != tmp[i]) m++; 19 int n = 0; 20 while(numbers[n] != tmp[j]) n++; 21 if(n == m){ 22 n++; 23 while(numbers[n] != tmp[j]) n++; 24 } 25 26 rs.push_back(m>n?n+1:m+1); 27 rs.push_back(m>n?m+1:n+1); 28 return rs; 29 }else if(sum < target){ 30 i++; 31 }else{ 32 j--; 33 } 34 } 35 return rs; 36 } 37 };
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步