【1337code ez series】twoSum 问题

Posted on 2018-01-28 22:24  Unkn0wnnnnn  阅读(127)  评论(0)    收藏  举报
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, and you may not use the same element twice.

Example:

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

 

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

return [01].

刚拿到题目一脸懵逼,脑袋里唯一的思路就是对该数组进行一个嵌套循环的操作,设置一个下标i并写一个for循环,在该for循环下嵌套一个for循环并设置一个下标j,遍历整个数组中是否有nums[i]+nums[j]=target的情况,如果有,则返回此时二者的下标。然而对于这问题来说,这样的一个算法的时间复杂度因为两个for循环的存在,时间复杂度为O(n^2),所以在考虑是否有一种可以降低整个算法的时间复杂度的方法呢? 在思考后觉得,可以通过map容器对该数组进行一个操作,提前将所需要遍历的数组存入map容器中,这样则可以牺牲空间从而赚得时间。所以,具体实现代码如下:

public:
    vector<int> twoSum(vector<int> nums, int target) {
        map<int,int>result;
        for(int i=0;i<nums.size();i++){
            if(result.count(target-nums[i])) {
                return {i, result[target - nums[i]]};
            }
            result[nums[i]]=i;
        }
    }
};

以这样的一个算法实现出来的时间复杂度为O(n).