leetcode1 Two Sum

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

UPDATE (2016/2/13):

The return format had been changed to zero-based indices. Please read the above updated description carefully.

题意:找出一个数组中两个数和为target的下标。

原始做法:双重循环,简单无脑,就是慢了点。

代码

vector<int> twoSum(vector<int>& nums, int target)
{
    vector<int> ans;
    int l = nums.size(),j,k;

    for(j=0;j<l-1;j++)
    {
        for(k=j+1;k<l;k++)
        {
            if(nums[j] + nums[k] == target)
            {
                ans.push_back(j);
                ans.push_back(k);
                break;
            }
        }
    }
    return ans;
}

优化做法:上面做法的时间复杂度O(n2),而使用map(unordered_map)来存储之前查询过的数据,可以达到O(n)的复杂度。
代码:
vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> ans;
        map<int, int> m;
        for(int i=0;i<nums.size();i++)
        {
            if(m.find(target-nums[i]) != m.end())
            {
                ans.push_back(m[target-nums[i]]);
                ans.push_back(i);
                break;
            }
            m[nums[i]] = i;
        }
        return ans;
    }

这里用map或者unordered_map都可以过,区别是map会比unordered_map慢一点。

查了资料,map对应的是JAVA中的TreeMap,而unordered_map对应HashMap,具体区别在以后的博客中继续讨论。



原文地址:https://www.cnblogs.com/puyangsky/p/5261563.html