栈&队列&哈希表&堆-python  https://blog.csdn.net/qq_19446965/article/details/102982047

1、O(1)时间插入、删除和获取随机元素

设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。

insert(val):当元素 val 不存在时,向集合中插入该项。
remove(val):元素 val 存在时,从集合中移除该项。
getRandom:随机返回现有集合中的一项。每个元素应该有相同的概率被返回。
示例 :

// 初始化一个空的集合。
RandomizedSet randomSet = new RandomizedSet();

// 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomSet.insert(1);

// 返回 false ,表示集合中不存在 2 。
randomSet.remove(2);

// 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
randomSet.insert(2);

// getRandom 应随机返回 1 或 2 。
randomSet.getRandom();

// 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
randomSet.remove(1);

// 2 已在集合中,所以返回 false 。
randomSet.insert(2);

// 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。
randomSet.getRandom();

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/insert-delete-getrandom-o1

class RandomizedSet(object):

    def __init__(self):
"""
Initialize your data structure here.
"""
self.nums = []
self.maps = {} def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val in self.maps:
return False self.nums.append(val)
self.maps[val] = len(self.nums) - 1
return True def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val not in self.maps:
return False # 将末尾的值移到待删除元素的位置
index = self.maps.get(val)
last_val = self.nums[-1]
self.nums[index] = last_val
self.maps[last_val] = index
# 删除最后一个元素
self.nums.pop()
# 删除被删除元素的index
del self.maps[val]
return True def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
return random.choice(self.nums)

2、O(1) 时间插入、删除和获取随机元素 - 允许重复

示例:

// 初始化一个空的集合。
RandomizedCollection collection = new RandomizedCollection();

// 向集合中插入 1 。返回 true 表示集合不包含 1 。
collection.insert(1);

// 向集合中插入另一个 1 。返回 false 表示集合包含 1 。集合现在包含 [1,1] 。
collection.insert(1);

// 向集合中插入 2 ,返回 true 。集合现在包含 [1,1,2] 。
collection.insert(2);

// getRandom 应当有 2/3 的概率返回 1 ,1/3 的概率返回 2 。
collection.getRandom();

// 从集合中删除 1 ,返回 true 。集合现在包含 [1,2] 。
collection.remove(1);

// getRandom 应有相同概率返回 1 和 2 。
collection.getRandom();

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/insert-delete-getrandom-o1-duplicates-allowed

1)把某个数在数组中出现的所有的位置用dict的形式存储下来

2)重复元素用set存下来,用于判断

3)删除一个数的时候,就是从这个 list 里随便拿走一个数(比如最后一个数)

class RandomizedCollection(object):

    def __init__(self):
"""
Initialize your data structure here.
"""
self.nums = []
self.maps = collections.defaultdict(set) def insert(self, val):
"""
Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
:type val: int
:rtype: bool
"""
self.nums.append(val)
self.maps[val].add(len(self.nums)-1)
return len(self.maps[val]) == 1 def remove(self, val):
"""
Removes a value from the collection. Returns true if the collection contained the specified element.
:type val: int
:rtype: bool
"""
if not self.maps[val]:
return False index = self.maps[val].pop()
self.nums[index] = None
return True def getRandom(self):
"""
Get a random element from the collection.
:rtype: int
"""
x = None
while x is None: # 注意:这里不能写成while not x:
x = random.choice(self.nums)
return x

3、 复制带随机指针的链表

给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。

要求返回这个链表的深拷贝

示例:

输入:
{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}

解释:
节点 1 的值是 1,它的下一个指针和随机指针都指向节点 2 。
节点 2 的值是 2,它的下一个指针指向 null,随机指针指向它自己。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/copy-list-with-random-pointer

首先,先复习一下正常链表的拷贝:

class Node(object):
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random

  

def copy_list(head):
if not head:
return None new_head = Node(head.val)
p = head
q = new_head
while p:
if p.next:
q.next = Node(p.next.val)
else:
q.next = None
p = p.next
q = q.next return new_head

此题还要存储一下random节点

class Solution(object):
def copyRandomList(self, head):
"""
:type head: Node
:rtype: Node
"""
if head == None:
return None maps = {}
new_head = Node(head.val, None, None)
maps[head] = new_head
p = head
q = new_head
while p:
q.random = p.random
if p.next:
q.next = Node(p.next.val, None, None)
maps[p.next] = q.next
else:
q.next = None
p = p.next
q = q.next p = new_head
while p:
if p.random:
p.random = maps.get(p.random)
p = p.next return new_head

4、 乱序字符串

给出一个字符串数组S,找到其中所有的乱序字符串(Anagram)。如果一个字符串是乱序字符串,那么他存在一个字母集合相同,但顺序不同的字符串也在S中。

所有的字符串都只包含小写字母

样例1:

输入:["lint", "intl", "inlt", "code"]
输出:["lint", "inlt", "intl"]

样例 2:

输入:["ab", "ba", "cd", "dc", "e"]
输出: ["ab", "ba", "cd", "dc"]

什么是Anagram?

  • 如果在更改字符顺序后它们可以相同,则两个字符串是anagram。

链接:https://www.lintcode.com/problem/anagrams/description

class Solution:
"""
@param strs: A list of strings
@return: A list of strings
"""
def anagrams(self, strs):
# write your code here
maps = collections.defaultdict(list)
for word in strs:
char_list = ''.join(sorted(word))
maps[char_list].append(word)
res = []
for word_list in maps.values():
if len(word_list) >= 2:
res += word_list
return res

5、最长连续序列

给定一个未排序的整数数组,找出最长连续序列的长度。

要求算法的时间复杂度为 O(n)。

示例:

输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-consecutive-sequence

第一种:O(nlogn)

先排序,再统计

class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) <= 1:
return len(nums) nums.sort()
length = 1
sum = 1
for i in range(1, len(nums)):
if nums[i] - nums[i-1] == 0:
continue if nums[i] - nums[i-1] == 1:
sum += 1
else:
if sum > length:
length = sum
sum = 1 if sum > length:
length = sum
return length

第二种:O(n)

HashSet 判断

class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
maps = set(nums)
length = 0 for num in nums:
if num in maps:
sum = 1
maps.remove(num)
l = num - 1
r = num + 1
while l in maps:
maps.remove(l)
l -= 1
sum += 1
while r in maps:
maps.remove(r)
r += 1
sum += 1
if length < sum:
length = sum return length

参考:九章算法讲解 https://www.jiuzhang.com/solution/

哈希表相关题目-python的更多相关文章

  1. 算法<初级> - 第二章 队列、栈、哈希表相关问题

    算法 - 第二章 数据结构 题目一 用数组实现大小固定的队列和栈(一面题) 数组实现大小固定栈 /*** * size是对头索引(initSize是固定大小) 也是当前栈大小 * size=下个进队i ...

  2. 12 哈希表相关类——Live555源码阅读(一)基本组件类

    12 哈希表相关类--Live555源码阅读(一)基本组件类 这是Live555源码阅读的第一部分,包括了时间类,延时队列类,处理程序描述类,哈希表类这四个大类. 本文由乌合之众 lym瞎编,欢迎转载 ...

  3. MySQL数据库(二)--库相关操作、表相关操作(1)、存储引擎、数据类型

    一.库相关操作 1.创建数据库 (1)语法 create database 数据库 charset utf8; (2)数据库命名规范 可以由字母.数字.下划线.@.#.$ 区分大小写 唯一性 不能使用 ...

  4. MySQL数据库(二)——库相关操作、表相关操作(一)、存储引擎、数据类型

    库相关操作.表相关操作(一).存储引擎.数据类型 一.库相关操作 1.创建数据库 (1)语法 create database 数据库 charset utf8; (2)数据库命名规范 可以由字母.数字 ...

  5. 使用Js脚本 修改控制IE的注册表相关设置(activex等)

    使用Js脚本 修改控制IE的注册表相关设置(activex等) 分类: PHP2012-12-05 18:51 2035人阅读 评论(2) 收藏 举报 脚本写法: <SCRIPT LANGUAG ...

  6. MySQL常用命令(数据库,表相关的命令)

    数据库相关命令 显示数据库列表 mysql> SHOW  DATABASES; 创建数据库 mysql> CREATE  DATABASE  库名; 如下,创建一个名为crashcours ...

  7. MYSQL初级学习笔记二:数据表相关操作及MySQL存储引擎!(视频序号:初级_5,7-22|6)

    知识点三:数据表相关操作(5,7-22) --------------------------------整型--------------------------------- --测试整型 CREA ...

  8. MySQL数据库(三)—— 表相关操作(二)之约束条件、关联关系、复制表

    表相关操作(二)之约束条件.关联关系.复制表 一.约束条件  1.何为约束 除了数据类型以外额外添加的约束 2.约束条件的作用 为了保证数据的合法性,完整性 3.主要的约束条件 NOT NULL # ...

  9. C#连接Oracle数据库,通过EF自动生成与数据库表相关的实体类

    C#连接Oracle数据库,通过EF自动生成与数据库表相关的实体类 ps:如需转载,请在转载文章明显处,i标注作者和原文地址 一.准备条件 需要自己电脑上已经安装了Oracle数据库,并且已经创建了相 ...

  10. 环链表相关的题目和算法[LeetCode]

    这篇文章讨论一下与链表的环相关的题目,我目前遇到的一共有3种题目. 1.判断一个链表是否有环(LeetCode相关题目:https://leetcode.com/problems/linked-lis ...

随机推荐

  1. 《黑马旅游网》综合案例六 BaseServlet 抽取

    BaseServlet抽取 减少Servlet的数量,现在是一个功能一个Servlet,将其优化为一个模块一个Servlet, 相当于在数据库中一张表对应一个Servlet,在Servlet中提供不同 ...

  2. 记一次修改vg name 引发的血案

    项目服务器安装完操作系统后,由于vg name 与转维标准不一致,故修改了vg name,那么案件由此发生 1.安装完系统后 /etc/fstab 默认为 2.修改vg name 和 lv name ...

  3. 068_Apex&Page中的ReadOnly 使用方式

    一.page页面遇到需要检索大量数据的处理方式需要时会用Readonly 通常,对单个Visualforce页面请求的查询可能无法检索超过50,000行. 在Read only模式下,此限制将放宽允许 ...

  4. Ubuntu下安装Node.js+ThreeJs

    以具有sudo特权的用户身份运行以下命令,以下载并执行NodeSource安装脚本 curl -sL https://deb.nodesource.com/setup_16.x | sudo -E b ...

  5. 4-20mA换算为实际值公式

    Ov = [(Osh - Osl) * (Iv - Isl) / (Ish - Isl)] + Osl 实际工程量 = [((实际工程量)的高限 - (实际工程量)的低限)*(lv - 4) / (2 ...

  6. unctfWP

    web: 签到:,更改学号,找规律,用笔记本记录出现的数据. 我太喜欢哔哩哔哩大学啦--中北大学:就往下面翻找flag,就会看见一个flag的语句,这个就是答案. ezgame-浙江师范大学:这个就是 ...

  7. 808.11ac的MAC层

    MAC层是802.11的主要功能部分.上层应用通过调用MAC层提供的接口原语调用MAC层的功能. 在内部,MAC由除了函数还有数据,叫MIB,存储MAC的各种参数.SME是一个单独的模块,用来跟接口函 ...

  8. JSR303校验

    JSR是Java Specification Requests的缩写,意思是Java 规范提案.是指向JCP(Java Community Process)提出新增一个标准化技术规范的正式请求.任何人 ...

  9. POD状态整理(持续更新)

    pendding Pod一直停留在Pending状态,可能表示,该Pod不能被调度到某一个节点上------我遇到的一个情况确实是这样的,因为我要mount的卷是在worker1上的,由于pod运行时 ...

  10. windos下激活python虚拟环境

    1.从终端中找到解释器的目录 2.cd到Scripts,输入激活命令activate  这样就表示激活成功了