【Two Sum】cpp
题目:
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
代码:
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { std::vector<int> ret_vector; std::map<int,int> value_index; for (int i = 0; i < numbers.size(); ++i) { const int gap = target - numbers[i]; if (value_index.find(gap) != value_index.end()) { ret_vector.push_back(std::min(i+1,value_index[gap]+1)); ret_vector.push_back(std::max(i+1,value_index[gap]+1)); break; } else { value_index[numbers[i]] = i; } } return ret_vector; } };
Tips:
元素无序且要求复杂度O(n)的,就可以用hashmap解决。
网上有的算法先遍历一遍numbers获得所有元素的map<value,index>,再进行后续的计算。这样的算法没有考虑数组元素重复的case
比如:
numbers = [0,2,4,0]
target = 0
===========================================
第二次过此题,大体思路非常明确。额外开一个hashmap,访问数组一次就搞定。
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> ret; unordered_map<int, int> value_index; for ( int i=0; i<nums.size(); ++i ) { if ( value_index.find(target-nums[i])!=value_index.end() ) { ret.push_back(i+1); ret.push_back(value_index[target-nums[i]]+1); break; } value_index[nums[i]] = i; } std::sort(ret.begin(), ret.end()); return ret; } };
tips:
有三个细节需要注意:
1. [3, 2, 4] 6 对于这种类型的,一定要把value_index[nums[i]]=i放在if语句的后面,要不然同一个元素3就被用了两次
2. 题目要返回的index并不是数组下标,而是数组下标加1,且返回的值要求有序
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?