LeetCode刷题必知的Python知识

1.数组操作

#创建数组
a = []
#添加元素
a.append(1)
a.insert(2,99)
#访问元素:用索引(下标)访问元素
temp = a[2]
#更新元素
a[2] = 99
#删除元素
a.remove(99)
a.pop(2)
a.pop()
#获取数组长度
size = len(a)
#遍历数组
for i in a:
    print(i)

for index,element in enumerate(a):
    print("Index at",index,"is:",element)

for i in range(0,len(a)):
    print("i=",i,"element:",a[i])
#查找某个元素
index = a.index(2)
#数组排序
a.sort()
a.sort(reverse = True)

2.链表操作

#创建链表
linkedlist = deque()
#添加元素
linkedlist.append(1)
linkedlist.insert(2,99)
#访问元素
element = linkedlist[2]
#搜索元素
index = linkedlist.index(99)
#更新元素
linkedlist[2] = 88
#删除元素
linkedlist.remove(88)
#长度
length = len(linkedlist)

3.队列操作

#创建队列
queue = deque()
#添加元素
queue.append(1)
#获取即将出队的元素
temp1 = queue[0]
#删除即将出队的元素
temp2 = queue.popleft()
#判断队列是否为空
len(queue) == 0
#遍历队列
while len(queue)!=0:
    temp = queue.popleft()
    print(temp)

4.栈操作

#创建栈
stack = []
#添加元素
stack.append(1)
#获取栈顶元素
stack[-1]
#删除栈顶元素
temp = stack.pop()
#栈的大小
len(stack)
#栈是否为空
len(stack) == 0
#栈的遍历(边删除边遍历)
while len(stack) > 0:
    temp = stack.pop()
    print(temp)

5.哈希表操作

#创建哈希表
hashTable = ['']*4
mapping = {}
#添加元素
hashTable[1] = 'lihua'
mapping[1] = 'lihua'
#修改元素
hashTable[1] = 'lisi'
mapping[1] = 'lisi'
#删除元素
hashTable[1] = ''
mapping.pop(1)
#获取元素
hashTable[3]
mapping[3]
#检查key是否存在
3 in mapping
#哈希表的长度,判断哈希表是否还有元素
len(mapping) == 0

6.哈希集合操作

#创建集合
s = set()
#添加元素
s.add(1)
#搜索元素
2 in s
#删除元素
s.remove(1)
#长度
len(s)

7.堆操作

#创建堆
import heapq
#创建最小堆
minheap = []
heapq.heapify(minheap)
#添加一个元素
heapq.heappush(minheap,10)
#删除堆顶元素
heapq.heappop(minheap)
#长度
len(minheap)
#边删除边遍历
while len(minheap)!= 0:
    print(heapq.heappop(minheap))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值