• [编程之法]2.2 寻找和为定值的两个数


    题目


    输入一个整数和一个整数数组,在数组中查找一对数,满足他们的和正好是输入的那个整数,如果有多对数的和等于输入的整数,输出任意一对即可。例如,如果输入数组[1,2,4,5,7,11,15]和整数15,那么由于4+11=15,因此表明存在两个数能相加为15。

    代码


    #include <iostream>
    #include <vector>
    #include <map>
    using namespace std;
    class Solution
    {
    public:
        bool hasTwoNumEqualVal(int val, vector<int> nums)
        {
            //利用map存储
            map<int, bool> hashtable;
            //将存在的值设为true
            for (auto i : nums)
                hashtable[i] = true;
            //判断value-i的值在hash表中是否存在,存在则为true
            for (auto i : nums)
                if (hashtable[val - i] == true)
                    return true;
            return false;
        }
    };

    思路


    采用空间换时间的方法,利用map存储已经存在的数,如果value-nums[i]存在,则表示结果为true。时间复杂度为O(n),空间复杂度为O(n)

    https://github.com/li-zheng-hao
  • 相关阅读:
    jquery 不支持$.browser
    js 双向绑定
    css3 省略号
    js生成txt文件
    Browser-sync
    Generator & yield write in sync way
    Charles
    缓动函数与动画
    让Safari使用Chrome的代理
    React 同构
  • 原文地址:https://www.cnblogs.com/lizhenghao126/p/11053672.html
Copyright © 2020-2023  润新知