[LeetCode] Two Sum 两数之和

博客围绕LeetCode题目展开,给定整数数组,需找出两数之和等于特定目标值的元素索引。解析中提到一种方法时间复杂度为O(n²)会超时,另一种用HashMap建立数值与坐标映射,时间复杂度为O(n),还给出了C++代码及unordered_map用法提示。

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

题目

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解析

寻找两个数,这两个数之和为一个特定的数,可以采用暴力搜索,但是时间复杂度为O(n2)O(n^2)O(n2),Time Limit Exceeded。另一种方法,使用HashMap,先建立数组中数值与其坐标位置之间的映射。HashMap是常数级的查找效率。这样,在遍历数组时,用target减去遍历到的数值,就是另一个需要的数字,然后再HashMap中查找其是否存在即可,但是查找到的数值不是遍历到的数值。整体过程:先遍历一遍数组,建立HashMap,然后再遍历一遍,开始查找,找到则记录下index。时间复杂度为O(n)O(n)O(n)

C++代码:

class Solution{
public:
	vector<int> twoSum(vector<int>& nums, int target){
		unordered_map<int, int> m;
		vector<int> res;
		// 遍历数组,建立HashMap
		for (int i = 0; i < nums.size(); ++i ){			
			m[nums[i]] = i;	
		}
		// 遍历数组,查找符合条件的数值
		for (int i=0; i < nums.size(); ++i){
			int t = target - nums[i];
			if (m.count(t) && m[t]!=i){
				res.push_back(i);
				res.push_back(m[t]);
				break;
			}
		}
		returen res;
	}
}

注意: unordered_map的用法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值