当前位置: 首页 > news >正文

8.8 哈希表简单 1 Two Sum 141 Linked List Cycle

1 Two Sum

在这里插入图片描述

class Solution {
public:vector<int> twoSum(vector<int>& nums, int target) {//给的target是目标sum 要返回vector<int> res(2,0);是在num中找加数//首先假设每个输入都是由唯一的结果,而且不适用相同的元素两次一共有n*(n-1)种情况//按照顺序返回ansvector<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;}
};

下方是哈希表解题:

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

在这里插入图片描述
在这里插入图片描述

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

http://www.lryc.cn/news/419283.html

相关文章:

  • 动态规划之——背包DP(完结篇)
  • Advanced IP Scanner - 网络扫描工具介绍
  • 数据库事务的四大特性ACID
  • ELK架构介绍
  • Vscode下ESP32工程函数定义无法跳转
  • liquibase.exception.LockException: Could not acquire change log lock.
  • 【多线程-从零开始-捌】阻塞队列,消费者生产者模型
  • 数据结构——栈(Stack)
  • 修改pom.xml为阿里云仓库并且让他生效
  • step13:qml/qt程序打包
  • 招聘求职小程序
  • 10分钟学会docker安装与使用
  • vue3、uniapp-vue3模块自动导入
  • Ubantu设置国内镜像(阿里云、华为云)
  • Redis远程字典服务器(3)——常用数据结构和单线程模型
  • [Qt][按钮类控件]详细讲解
  • 数据结构(5.5_2)——并查集
  • Java Web —— 第四天(Maven)
  • 2024年电脑录屏软件推荐:捕捉屏幕,记录生活,分享精彩
  • oracle 增删改查字段
  • 给不规则的shapeGeometry贴图
  • 网络层IP协议报头字段的认识
  • Linux部署MySQL8.0
  • 二叉树中的深搜
  • 固态继电器行业知识详解
  • 【practise】数组中出现次数超过一半的数字
  • RAGFlow v0.9 重磅升级,支持 GraphRAG,开启下一代 RAG 之旅!
  • MySQL的InnoDB的页里面存了些什么
  • SQL Server 事务
  • qt quick实现的水波纹特效:横向波纹、纵向波纹效果