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;
    }
};
相关推荐
三毛的二哥1 天前
BEV:典型BEV算法总结
人工智能·算法·计算机视觉·3d
南宫萧幕1 天前
自控PID+MATLAB仿真+混动P0/P1/P2/P3/P4构型
算法·机器学习·matlab·simulink·控制·pid
故事和你911 天前
洛谷-数据结构1-4-图的基本应用1
开发语言·数据结构·算法·深度优先·动态规划·图论
我叫黑大帅1 天前
为什么map查找时间复杂度是O(1)?
后端·算法·面试
炽烈小老头1 天前
【每天学习一点算法 2026/04/20】除自身以外数组的乘积
学习·算法
skilllite作者1 天前
AI agent 的 Assistant Auto LLM Routing 规划的思考
网络·人工智能·算法·rust·openclaw·agentskills
py有趣1 天前
力扣热门100题之不同路径
算法·leetcode
_日拱一卒1 天前
LeetCode:25K个一组翻转链表
算法·leetcode·链表
啊哦呃咦唔鱼1 天前
LeetCodehot100-394 字符串解码
算法
小欣加油1 天前
leetcode2078 两栋颜色不同且距离最远的房子
数据结构·c++·算法·leetcode·职场和发展