首页 > 其他 > 详细

two Sum ---- LeetCode

时间:2016-03-29 23:36:14      阅读:256      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!