[LeetCode] 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
新建一个数组,分别保存原数组的值和索引,并对新数组按值排序,之后按照2Sum的方法,左右两根指针就可以找解了。O(n)
1 struct Node 2 { 3 int val; 4 int index; 5 Node(){} 6 Node(int v, int idx):val(v), index(idx){} 7 }; 8 9 bool compare(const Node &lhs, const Node &rhs) 10 { 11 return lhs.val < rhs.val; 12 } 13 14 class Solution { 15 public: 16 vector<int> twoSum(vector<int> &numbers, int target) { 17 // Start typing your C/C++ solution below 18 // DO NOT write int main() function 19 vector<Node> a; 20 for(int i = 0; i < numbers.size(); i++) 21 a.push_back(Node(numbers[i], i + 1)); 22 sort(a.begin(), a.end(), compare); 23 24 int i = 0; 25 int j = numbers.size() - 1; 26 while(i < j) 27 { 28 int sum = a[i].val + a[j].val; 29 if (sum == target) 30 { 31 vector<int> ret; 32 int minIndex = min(a[i].index, a[j].index); 33 int maxIndex = max(a[i].index, a[j].index); 34 ret.push_back(minIndex); 35 ret.push_back(maxIndex); 36 return ret; 37 } 38 else if (sum < target) 39 i++; 40 else 41 j--; 42 } 43 } 44 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】