leetcode_001两数之和

1. 题目

两数之和

2. 题意

找到数组中和为给定值的两个值的坐标。

3. 题解

3.1 暴力

两重循环,直接列举出来。

cpp 复制代码
class Solution1 {
public:
    vector<int> twoSum(vector<int>& nums, int target) {


        vector<int> res;
        int size = nums.size();
        for (int i = 0;i < size; ++i) {
            for ( int j = i + 1; j < size; ++j) {
                if (nums[i] + nums[j] == target) {
                    res={i,j};
                    return res;
                }
            }
        }

        return res;
    }
};

3.2 哈希表

查找hash(val) 是否存在,在表中则取出得到答案;否则将当前位置存入表中hash(target - val)

cpp 复制代码
class Solution2 {
public:
    vector<int> twoSum(vector<int>& nums, int target) {

        unordered_map<int,int> um;
        int sz = nums.size();

        vector<int> res;
        for ( int i = 0;i < sz; ++i) {
            if ( um.find(nums[i]) != um.end() ){
                res = {um[nums[i]], i};
                return res;
            }
            else {
                um[target - nums[i]] = i;
            }
        }


        return res;
    }
};
相关推荐
中文英文-我选中文6 分钟前
排序算法的理解
算法·排序算法
我明天再来学Web渗透27 分钟前
【hot100-java】【二叉树的层序遍历】
java·开发语言·数据库·sql·算法·排序算法
数据分析螺丝钉1 小时前
力扣第240题“搜索二维矩阵 II”
经验分享·python·算法·leetcode·面试
no_play_no_games1 小时前
「3.3」虫洞 Wormholes
数据结构·c++·算法·图论
￴ㅤ￴￴ㅤ9527超级帅1 小时前
LeetCode hot100---数组及矩阵专题(C++语言)
c++·leetcode·矩阵
五味香1 小时前
C++学习,信号处理
android·c语言·开发语言·c++·学习·算法·信号处理
毕小宝2 小时前
逻辑回归(下): Sigmoid 函数的发展历史
算法·机器学习·逻辑回归
小叮当爱咖啡2 小时前
DenseNet算法:口腔癌识别
算法
希望有朝一日能如愿以偿2 小时前
算法(食物链)
算法
鱼跃鹰飞2 小时前
Leecode热题100-295.数据流中的中位数
java·服务器·开发语言·前端·算法·leetcode·面试