0
点赞
收藏
分享

微信扫一扫

【LeetCode】1两数之和

东言肆语 2022-04-16 阅读 113
c++

学了那么久的C++,今天才发现除了最最基础的语法啥也不会。摊手。

代码来自力扣

// 时间复杂度:O(n)
// 空间复杂度:O(n)
// 空间换时间
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> map;

        for (int i = 0; i < nums.size(); i++) {
            int x = nums[i];
            if (map.count(target - x)) {
                int index = map[target - x];
                return {i, index};
            }
            map[x] = i;
        }

        return {};
    }

利用哈希做的。

其中,

unordered_map<int, int> map;

 和普通map的区别就是一个有序一个无序。

count()是个计数函数

顺便,最近学python发现函数可以返回多个参数(其实是一个list),还觉得好方便啊别的为啥没有。

然后今天才知道C++也可以。。。

学无止境。

 

举报

相关推荐

LeetCode 1 两数之和

Leetcode 1:两数之和

LeetCode-1-两数之和

LeetCode1.两数之和

【LeetCode】1. 两数之和

LeetCode 1.两数之和

0 条评论