1. Two Sum

来源:互联网 发布:淘宝店铺改名生效 编辑:程序博客网 时间:2024/06/05 15:18

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

方法一是使用暴力求解,时间复杂度为n^2,当数据很大时,效率很低
方法二是先排序再判断,时间复杂度是nlgn。开始用快排,或其他排序方法对nums排序,然后用两个指针从前后开始进行判断,然后从i=0,j=end开始和末位的两个数字开始,计算两个之和sum,若sum大于目标值target,则需要一个较小的因子,j–;反之,i++;直至找到最终的结果。
这里没有返回标号
方法三是用哈希,时间复杂度是o(n). 哈希表在理想的情况下查找一个数是O(1),新的c++11中增加了unordered_map;

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        vector<int>res(2,-1);        unordered_map<int,int>m;        for(int i=0;i<nums.size();i++){            int t=target-nums[i];            if(m.find(t)==m.end()){                m[nums[i]]=i;            }else{                res[0]=m[t];                res[1]=i;                break;            }        }        return res;    }};

如果使用stl中的map,则时间复杂度是nlgn, stl中的map容器的底层实现是红黑树,查找find需要的时间是lgn,外层遍历是n。

0 0