【LeetCode001算法/编程练习C++】--twoSum //从816ms到16ms的优化过程

题目://在一个Vector里找到两个和为指定数的下标(假设有且仅有一对)

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.

Example:

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

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


------------------------------------------------------解法分割线-----------------------------------------------


最简单无脑的一种解法:(找两圈)//时间花费为:816ms,击败了4%的人…………

class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) {
		vector<int> answer;
		for (int i = 0; i<nums.size(); i++) {
		    for(int j=i+1;j<nums.size();j++){
		        if(nums[i]+nums[j]==target){
		            answer.push_back(i);
		            answer.push_back(j);
		        }
		    }
		    
		}
		return answer;
	}
};
运行结果如图:




调用map之后的解法://42ms,时间复杂度为O(n),效率大大提升了!

class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) {
		vector<int> answer;
		map<int, int> mapping;
		int tofind;
		for (int i = 0; i<nums.size(); i++) {
			tofind = target - nums[i];
		if (mapping[tofind] != 0) {
				answer.push_back(mapping[target - nums[i]] - 1);
				answer.push_back(i);
			}
			mapping[nums[i]] = i + 1;
		}
		return answer;
	}
};


调用unordered_map的解法://22ms

//后来发现,mapping[tofind]!=0也会在mapping里添加一个映射,也就是把tofind加入到了map里,不过好像对结果没什么影响,但肯定不好。

class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) {
		vector<int> answer;
		unordered_map<int, int> mapping;
		int tofind;
		for (int i = 0; i<nums.size(); i++) {
			tofind = target - nums[i];
		if (mapping[tofind] != 0) {
				answer.push_back(mapping[target - nums[i]] - 1);
				answer.push_back(i);
			}
			mapping[nums[i]] = i + 1;
		}
		return answer;
	}
};


参考TopSolution修改后的代码,调用.find()函数,速度更快://16ms

class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) {
		vector<int> answer;
		unordered_map<int, int> mapping;
		for (int i = 0; i<nums.size(); i++) {
		if (mapping.find(target-nums[i]) != mapping.end()) {
				answer.push_back(mapping[target - nums[i]] - 1);
				answer.push_back(i);
			}
			mapping[nums[i]] = i + 1;
		}
		return answer;
	}
};


运行结果如图:



祝程序猿和科研狗永远黑发浓密~



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

朱铭德

五毛也是爱٩(●´৺`●)૭

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值