码迷,mamicode.com
首页 > 其他好文 > 详细

two Sum ---- LeetCode

时间:2016-03-29 23:37:17      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

Solution 1: 

class Solution 
{
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        unordered_map<int, int> myMap;
        vector<int> result;
        
        for(size_t i = 0; i < nums.size(); ++i)
        {
            myMap[nums[i]] = i;
        }
            
        for(size_t i = 0; i < nums.size(); ++i)
        {
            const int gap = target - nums[i];
            auto it = myMap.find(gap);
            if(it != myMap.end() && it->second != i)
            {
                result.push_back(i);
                result.push_back(myMap[gap]);
                break;  // Assume that each input would have 
// exactly one solution
} } return result; } };

Solution 2:  暴力查找,超时

class Solution 
{
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        vector<int> result;
        for(size_t i = 0; i < nums.size(); ++i)
        {
            for(size_t j = i + 1; j < nums.size(); ++j)
            {
                if(nums[i] + nums[j] == target)
                {
                    result.push_back(i);
                    result.push_back(j);
                    break;
                }
            }
        }
        return result;
    }
};

Solution 3: 

 

two Sum ---- LeetCode

标签:

原文地址:http://www.cnblogs.com/xuyan505/p/5335210.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!