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

相关推荐
wclass-zhengge2 小时前
数据结构与算法篇(树 - 常见术语)
数据结构·算法
夜雨翦春韭2 小时前
【代码随想录Day31】贪心算法Part05
java·数据结构·算法·leetcode·贪心算法
C++忠实粉丝8 小时前
前缀和(8)_矩阵区域和
数据结构·c++·线性代数·算法·矩阵
ZZZ_O^O8 小时前
二分查找算法——寻找旋转排序数组中的最小值&点名
数据结构·c++·学习·算法·二叉树
代码雕刻家9 小时前
数据结构-3.9.栈在递归中的应用
c语言·数据结构·算法
Kalika0-011 小时前
猴子吃桃-C语言
c语言·开发语言·数据结构·算法
代码雕刻家11 小时前
课设实验-数据结构-单链表-文教文化用品品牌
c语言·开发语言·数据结构
小字节,大梦想12 小时前
【C++】二叉搜索树
数据结构·c++
我是哈哈hh13 小时前
专题十_穷举vs暴搜vs深搜vs回溯vs剪枝_二叉树的深度优先搜索_算法专题详细总结
服务器·数据结构·c++·算法·机器学习·深度优先·剪枝
丶Darling.13 小时前
LeetCode Hot100 | Day1 | 二叉树:二叉树的直径
数据结构·c++·学习·算法·leetcode·二叉树