Two sum题解

来源:互联网 发布:收获日2优化 编辑:程序博客网 时间:2024/06/18 03:58

题干:
Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

Difficulty: Medium
翻译:
给一个数列和一个目标数字target,在数列中找到两个数字使它们的和等于target,并且两个数字要小的在前大的在后,你可以假定只有唯一解
分析:
题目难度标注是中等,实际上是easy题,leetcode初期很多题目medium难度跟后来新加题的esay差不多,O(n²)的解法显而易见,遍历两遍就行,然而这样就太无聊了,两个数假设一个是num1一个是num2,公式为num1+num2=target,怎么样,显而易见,当我们给定一个num1之后,实际上问题就是找target-num1,并且保证这俩数不是同一个点。
在所有的数据结构中,查找元素最快的就是hash表,理论上时间复杂度是O(1),在c++中,我们用map可以方便的构造hash表:

class Solution {public:    vector<int> twoSum(vector<int>& numbers, int target) {        vector<int> ret;        if (numbers.size() <= 1)            return ret;        map<int, int> hash_map;        //把数列存储在hash中        for (int i = 0; i < numbers.size(); i++)            hash_map[numbers[i]] = i;        for (int i = 0; i < numbers.size(); i++) {            int rest_val = target - numbers[i];            if (hash_map.find(rest_val) != hash_map.end()) {                int index = hash_map[rest_val];                //同样的点舍弃                if (index == i) continue;                //满足num1<num2                if (index < i) {                    ret.push_back(index + 1);                    ret.push_back(i + 1);                    return ret;                }                else {                    ret.push_back(i + 1);                    ret.push_back(index + 1);                    return ret;                }            }        }    }};

hash表查找复杂度O(1),建立复杂度O(n),空间O(n),所以是O(n),O(n)的算法,虽然建立hash表是O(n)的时间复杂度,然而线性系数非常小,我们在研究问题的时候大多不考虑线性系数,实际上,同样时间复杂度的算法,线性系数的不同,运行时间可以相差10倍,这点在后面复杂题目上会有体现

0 0
原创粉丝点击