首页 > 其他 > 详细

2Sum

时间:2017-01-06 01:28:10      阅读:179      评论:0      收藏:0      [点我收藏+]

用哈希表(unordered_map)使得时间复杂度从O(n*n)降到O(n),空间复杂度从O(1)增到O(n);一边找一边插入哈希表

注意

在C++11以前要使用unordered_map需要

#include<tr1/unordered_map>//在unordered_map之前加上tr1库名,

using namespace std::tr1;//与此同时需要加上命名空间

class twoSum {
public:
    vector<int> f1(vector<int>& nums, int target) {
        unordered_map<int, int> hash;
        vector<int> result;
        for (int i = 0; i < nums.size(); i++) {
            int numToFind = target - nums[i];
            if (hash.find(numToFind) != hash.end()) {
                result.push_back(hash[numToFind]);
                result.push_back(i);
                return result;
            }
            hash[nums[i]] = i;
        }
        return result;
    }
};

 

2Sum

原文:http://www.cnblogs.com/lzd233/p/6254628.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!