8.8 哈希表简单 1 Two Sum 141 Linked List Cycle

1 Two Sum

cpp 复制代码
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        //给的target是目标sum 要返回vector<int> res(2,0);是在num中找加数
        //首先假设每个输入都是由唯一的结果,而且不适用相同的元素两次一共有n*(n-1)种情况
        //按照顺序返回ans
        vector<int> res(2,0);
        //暴力解题
        int n = nums.size();
        for(int i = 0 ; i < n ; i++){
            for(int j = i+1 ; j < n ; j++){
                if(nums[i] + nums[j] == target){
                    res[0] = i;
                    res[1] = j;
                    return res;
                }
            }
        }
        return res;

    }
};

下方是哈希表解题:

cpp 复制代码
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int n = nums.size();
        //使用target - nums[i]
        //哈希表,前者入哈希,后者查哈希
        unordered_map<int,int> hash;
        for(int i = 0 ; i < n ;i ++){
            if(hash.find(target - nums[i]) != hash.end()){
                return {hash[target - nums[i]] , i};
            }
            hash[nums[i]] = i;
        }
        return {};

    }
};

141 Linked List Cycle


cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        int pos = -1;
        //哈希表存储什么?
        unordered_map<ListNode*,int> hash;
        ListNode *p = head;
        //一定要全部遍历吗?
        int i = 0;
        if(p == nullptr || p->next == nullptr){
            return false;
        }
        //怎么就能判定 p指向了之前的结点
        while(p){
            if(hash.find(p) != hash.end()){
                pos =  hash[p];
                return true;
            }
            hash[p] = i;
            i++;
            p = p->next;
        }
        return false;
    }
};

要求空间复杂度为O(1)使用快慢指针。

相关推荐
丶Darling.13 分钟前
26考研 | 王道 | 数据结构 | 第八章 排序
数据结构·考研·排序算法
我也不曾来过11 小时前
list底层原理
数据结构·c++·list
mit6.8242 小时前
[贪心_7] 最优除法 | 跳跃游戏 II | 加油站
数据结构·算法·leetcode
keep intensify2 小时前
通讯录完善版本(详细讲解+源码)
c语言·开发语言·数据结构·算法
shix .3 小时前
2025年PTA天梯赛正式赛 | 算法竞赛,题目详解
数据结构·算法
egoist20233 小时前
【C++指南】告别C字符串陷阱:如何实现封装string?
开发语言·数据结构·c++·c++11·string·auto·深/浅拷贝
Gsen28194 小时前
AI大模型从0到1记录学习 数据结构和算法 day20
数据结构·学习·算法·生成对抗网络·目标跟踪·语言模型·知识图谱
一定要AK4 小时前
天梯——L1-110 这不是字符串题
数据结构·c++·算法
2401_858286115 小时前
E47.【C语言】零散的练习题(1)
c语言·数据结构·算法·指针
SsummerC12 小时前
【leetcode100】组合总和Ⅳ
数据结构·python·算法·leetcode·动态规划