LeetCode_TwoSum、C++解法

来源:互联网 发布:php 提现到银行卡 编辑:程序博客网 时间:2024/06/06 00:44

时间复杂度O(n),利用C++STL库函数就可以解决问题;
当然网上还有一种解法,排序+二分,时间复杂度也可以是O(n),这里就不写了


这里要特别说明的是:
本来我是想用hash_map来写这个程序,但是发现VS2017报错,hash_map is deprecated and will be removed
意思是:hash_map已经被弃用
确实在MSDN的API文档里面有这句话This API is obsolete. The alternative is unordered_map Class.
AC代码如下

std::vector<int> twoSum(std::vector<int>& nums, int target) {    std::vector<int> res;    std::unordered_map<int, int> hashs;    for (int i = 0; i < nums.size(); i++)    {        if (hashs.end() != hashs.find(target - nums[i])) {            res.push_back(hashs[target - nums[i]]);            res.push_back(i);            return res;        }        hashs.insert(std::make_pair(nums[i], i));    }    return res;}
原创粉丝点击