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

相关推荐
想要成为糕糕手13 小时前
前端必修课:JavaScript 数组与数据结构底层逻辑全解析
javascript·数据结构·面试
tyung16 小时前
Go 手写 Wait-Free SPSC 无界队列:无 CAS、无锁、泛型节点池
数据结构·后端·go
Chen_harmony16 小时前
一、数据结构概念和复杂度计算
数据结构
小欣加油16 小时前
leetcode287寻找重复数
数据结构·c++·算法·leetcode
fie888918 小时前
LBP + HOG 特征检测与识别 MATLAB 实现
数据结构·算法·matlab
退休倒计时19 小时前
【每日一题】LeetCode 15. 三数之和 TypeScript
数据结构·算法·leetcode·typescript
AbandonForce20 小时前
滑动窗口:定长滑动窗口与不定长滑动窗口
数据结构·c++·算法
炸薯条!20 小时前
二叉树的链式表示(2)
java·数据结构·算法
YHHLAI21 小时前
JavaScript 数据结构精讲:数组底层与实战避坑
开发语言·javascript·数据结构
Coder-magician21 小时前
《代码随想录》刷题打卡day12:二叉树part02
数据结构·c++·算法