1. Two Sum

来源:互联网 发布:windows 轻量级虚拟机 编辑:程序博客网 时间:2024/06/06 00:55


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找出对应的下表iresult.push_back(i);//放入当下的下标ireturn 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;}//TestSolution test;vector<int> result = test.twoSum(ls, 100);if (result.size() != 0){cout << result[0] << " " << result[1] << endl;}return 0;}


0 0
原创粉丝点击