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)使用快慢指针。

相关推荐
OKkankan9 分钟前
红黑树的原理及实现
开发语言·数据结构·c++·算法
Eward-an25 分钟前
【详细解析】删除有序数组中的重复项 II
数据结构·算法
Book思议-35 分钟前
线性表之顺序表入门:顺序表从原理到实现「增删改查」
数据结构·算法
I_LPL38 分钟前
day52 代码随想录算法训练营 图论专题6
java·数据结构·算法·图论
小鸡吃米…1 小时前
Python线程同步
开发语言·数据结构·python
XW01059991 小时前
5-6统计工龄
数据结构·python·算法
样例过了就是过了1 小时前
LeetCode热题100 电话号码的字母组合
数据结构·c++·算法·leetcode·dfs
big_rabbit05022 小时前
[算法][力扣226]翻转一颗二叉树
数据结构·算法·leetcode
uesowys2 小时前
华为OD算法开发指导-数据结构-图
数据结构·算法·华为od
实心儿儿2 小时前
算法3:链表分割
数据结构·算法·链表