力扣| 哈希的count |使用哈希表来存储所有已经访问过的节点

 环形链表:思路:如果head经过的节点之前已经遇到过了,说明就是环形链表,返回true。

先创建一个哈希表seen存储值

使用count方法:hash.count(key) // 该函数:用以统计key值在unordered_map中出现的次数。c++ unordered_map不允许有重复的key。因此,如果key存在,则count返回1,如果不存在,则count返回0

所以如果count(head)== 1的话就说明是环形链表,return true。

再把节点插入到哈希表中遍历下一个(必须,如果不插入的话会超时)

class Solution {
public:
    bool hasCycle(ListNode *head) {
        unordered_set<ListNode*> seen;
        while (head != nullptr) {
            if (seen.count(head)) {
                return true;
            }
            seen.insert(head);
            head = head->next;
        }
        return false;
    }
};

相关推荐

  1. rust

    2024-03-24 15:46:01       28 阅读
  2. --+滑动子块--串联所有单词子串

    2024-03-24 15:46:01       14 阅读
  3. STL容器之补充——桶实现

    2024-03-24 15:46:01       17 阅读
  4. 面试经典题之

    2024-03-24 15:46:01       41 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-24 15:46:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-24 15:46:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-24 15:46:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-24 15:46:01       18 阅读

热门阅读

  1. 数据仓库——大维度问题

    2024-03-24 15:46:01       22 阅读
  2. 蓝桥杯day9刷题日记

    2024-03-24 15:46:01       22 阅读
  3. 支持向量和非支持向量

    2024-03-24 15:46:01       20 阅读
  4. hive 3.1.3 搭建

    2024-03-24 15:46:01       16 阅读
  5. python中的协程使用

    2024-03-24 15:46:01       18 阅读
  6. Python程序设计 类与对象

    2024-03-24 15:46:01       19 阅读