LeetCode OJ:Two Sum(两数之和)

本文介绍了一种解决“两数之和”问题的有效算法。该算法通过使用哈希表来存储数组元素及其索引,从而快速查找目标值对应的一对整数。文章提供了C++与Java两种语言的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

给一个vector,一个value,要求求出vector之内的两数相加之和等于value的两个index。

这里的基本思想是用一个map先来保存vector元素的值与他们对应的index,然后循环vector,用value减去每个数之后,把差值直接放到map里面去寻找
看能不能找到对应的index,大体上就是这个思想,下面详见代码:

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         map<int, int> index;
 5         vector<int> result;
 6         int sz = nums.size();
 7         for (int i = 0; i < sz; ++i){
 8             index[nums[i]] = i;
 9         }
10         map<int, int>::iterator it;
11         for (int i = 0; i < sz; ++i){
12             if ((it = index.find(target - nums[i])) != index.end()){
13                 if (it->second == i) continue;//这一步要注意,防止找到的index与当前的i是相等的
14                 result.push_back(i + 1);
15                 result.push_back(it->second + 1);
16                 break;
17             }
18         }
19         return result;
20     }
21 };

 附上java版本的代码,方法比上面简洁一点。不过道理还是基本一样的:

 1 public class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
 4         int [] result = new int[2];
 5         for(int i = 0; i < nums.length; ++i){
 6             if(m.containsKey(nums[i])){
 7                 int index = m.get(nums[i]);
 8                 result[0] = index + 1;
 9                 result[1] = i + 1;
10                 break;
11             }else{
12                 m.put(target-nums[i] ,i);//很关键!
13             }
14         }
15         return result;
16     }
17 }

 

转载于:https://www.cnblogs.com/-wang-cheng/p/4856032.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值