1. Two Sum


Given an array ofintegers, return indices of the two numbers such that they add up to a specifictarget. 

You may assumethat each input would have exactly one solution, and you may not use the sameelement twice.(假设只有一个结果,即查询到一次结果就终止)

 

Example:

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

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

return [0, 1].

 

**解题思路:其实这道题很简单,就是求解一个目标数在指定的数组中是否有和解,有就行,返回第一次得到和解的两个数的下标;那么思路肯定是遍历数组,双层遍历一下就可以得到结果,但是这样是很浪费时间和空间的,是否能只遍历一遍就可以得到结果呢。只遍历一遍那么面临着一个问题,那就是如何同时记录遍历过数字对应的下标和数字本身;这肯定是成对的,那么首先想到的是map,利用其其元素是对的属性,而且map提供了find函数,查找简单;但本题还可以更快,因为我们只是要查找,不用考虑map里面是否是有序的,那么重点就是利用unordered_map的查找复杂度是常数属性降低时间。

/* undorder_map运用,  
   随机数的产生,
   万天根 2017.3.21
   Leetcode1
 */
#include<iostream>
#include<vector>
#include<unordered_map>
#include<time.h>
#include<stdlib.h>
using namespace std;
class Solution {
public:
	vector<int> twoSum(vector<int> &numbers, int target) {
		unordered_map<int, int> uMap;
		vector<int> result;
		int  i,find;
		uMap[numbers[0]] = 0;// 在map 中将number中的元素作为key,i下标作为key对应的内容
		for (i = 0; i < numbers.size(); i++) {
			find = target - numbers[i];    //查找的目标
			if (uMap.find(find) != uMap.end()) {
				result.push_back(uMap[find]);//通过key值find找出对应的下表i
				result.push_back(i);//放入当下的下标i
				return result;
			}
			uMap[numbers[i]] = i;//没查找到时,将现在numbers[i],i 作为一对pair放入map中。
		}
		return result;
	}
};
int main() {
	vector<int> ls;
	//随机数的产生方法 rand每次运行前会调用srand初始化自身,所以要给srand 不同的seed 才能使得rand产生不同的值
	srand((unsigned)time(NULL));
	for (int i = 0; i < 100; i++) {
		int pt = rand() % 100;
		ls.push_back(pt);
	}
	for (int i = 0; i < 100; i++) {
		cout << ls[i]<< endl;
	}
	//Test
	Solution test;
	vector<int> result = test.twoSum(ls, 100);
	if (result.size() != 0){
		cout << result[0] << " " << result[1] << endl;
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值