中山大学算法课程题目详解(第一周)

问题描述:

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].

解决方法:

拿到题目,还是很自然地想到用两层for循环进行暴力求解,具体代码如下:

vector<int> twoSum(vector<int>& nums, int target) {
	vector<int> answer;
	for (int i = 0; i < nums.size(); i++) {
		int flag = target - nums[i];
		for (int j = i + 1; j < nums.size(); j++) {
			if (flag == nums[j]) {
				answer.push_back(i);
				answer.push_back(j);
				break;
			}
		}
	}
	return answer;
}
发现leedcode网站其实还是给过的,其实这是一个O(n^2)时间复杂度的算法,一旦数据量变大,耗费的时间必定很长。

采用map减少时间复杂度
思路是循环一次,每次都判断当前数组索引位置的值在不在map里,不在的话,加入进去,key为数值,value为它的索引值;在的话,取得他的key,记为n(此时n一定小于循环变量i),接下来再在map中查找(target-当前数值)这个数,利用了map中查找元素时间为常数的优势,如果找到了就结束,此处需要注意的是,如果数组中有重复的值出现,那么第二次出现时就不会加入到map里了,比如3,4,3,6;target=6时,当循环到第二个3时,也可以得到正确结果。代码如下:
vector<int> twoSum(vector<int>& nums, int target) {
	vector<int> answer;
	map<int, int> hmap;
	for (int i = 0; i < nums.size(); i++) {
		if (!hmap.count(nums[i])) {
			hmap.insert(pair<int, int>(nums[i], i));
		}
		if (hmap.count(target - nums[i])) {
			int n = hmap[target - nums[i]];
			if (n < i) {
				answer.push_back(n);
				answer.push_back(i);
				return answer;
			}
		}
	}
	return answer;
}
时间复杂度是O(n),比上面的暴力求解法少了好多





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值