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

相关推荐
Yang_jie_0315 小时前
笔记:数据结构(栈是否使用底指针以及头指针的初始化值)
数据结构·笔记·算法
lueluelue4717 小时前
LeetCode:滑动窗口
数据结构·算法·leetcode
码少女18 小时前
数据结构——冒泡排序及优化
数据结构·算法·排序算法
青梅橘子皮18 小时前
string---入门OJ题(1)
数据结构·算法
小高Baby@18 小时前
单链表的删操作
数据结构·算法·golang
qq_4542450318 小时前
BasicMethod.Map 设计框架:8 个并行基础模块的数学根基与实现
数据结构·算法·c#
青山木19 小时前
Hot 100 --- 二叉树与递归
java·数据结构·算法·leetcode·深度优先
ysa05103020 小时前
【板子】树上启发式合并
数据结构·c++·笔记·算法
2301_8002561121 小时前
数据结构基础期末复习例题
数据结构·算法
tachibana221 小时前
hot100 将有序数组转换为二叉搜索树(108)
java·数据结构·算法·leetcode