数组Array
LC485 最大连续1的个数
①一次遍历法
if nums is None or len(nums)==0:
return 0
count=0 if nums[0]==0 else 1
result=count
for i in range(1,len(nums)):
if nums[i]==1:
count+=1
else:
count=0
result=max(result,count)
return result
②动态规划法
if nums is None or len(nums)==0:
return 0
nums[0]=0 if nums[0]==0 else 1
result=nums[0]
for i in range(1,len(nums)):
if nums[i]==1:
nums[i]=nums[i-1]+1
else:
nums[i]=0
result=max(result,nums[i])
return result
LC283 移动零到数组末端
index=0
for num in nums:
if num!=0:
nums[index]=num
index+=1
for i in range(index,len(nums)):
nums[i]=0
LC27 移除数组中等于val的元素(双指针法)
if nums is None or len(nums)==0:
return 0
l,r=0,len(nums)-1
while l<r:
while(l<r and nums[l]!=val):#要有l<r这个条件
l+=1#找到第一个为val的数
while(l<r and nums[r]==val):
r-=1#找到第一个人不为val的值
nums[l],nums[r]=nums[r],nums[l]#交换
return l if nums[l]==val else l+1#l追到r上的话是l
链表LInked LIst
LC203 移除链表里元素等于val的元素(用到head dummy(prev))
dummy=ListNode(0)
dummy.next=head
prev=dummy
while head is not None:
if head.val==val:
prev.next=head.next
else:
prev=prev.next
head=head.next
return dummy.next
LC206 反转链表*
①迭代法O(N) O(1) 12345-21345-32145-43215-54321 从前往后反转
dummy=ListNode(0)
dummy.next=head
while(head!=None and head.next!=None):
dnext=dummy.next#值会变 先保存下来
hnext=head.next#head一直是1.后面head和dnext不是同一个数
dummy.next, head.next,hnext.next=hnext,hnext.next,dnext#有顺序的
return dummy.next
None ↑ None ↑
②递归法1→2→3→4→5→NULL (竖着) 1→2→3→4(head)←5 1→2→3(head)←4←5
O(N) O(N) 从下往上改变箭头方向
if not head or not head.next:#它们为空时
return head
p=self.reverseList(head.next)#层层递归下去找到满足为空条件时的head时开始从上一层运算
head.next.next=head
head.next=None
return p
队列Queue
LC933 最近的请求次数(类、方法)*
def __init__(self):
self.q=deque()#命名self.q
def ping(self, t: int) -> int:
self.q.append(t)
while (len(self.q)>0 and t-self.q[0]>3000):#必须用while 不能用if
self.q.popleft()
return len(self.q)
LC225 用队列实现栈(用两个队列)*
def __init__(self):
"""Initialize your data structure here."""
self.queue1 = collections.deque()#self.q1=deque()也可以
self.queue2 = collections.deque()
def push(self, x: int) -> None:#q1为栈
"""Push element x onto stack."""
self.queue2.append(x)
while self.queue1:
self.queue2.append(self.queue1.popleft())#把队列1的数放到队列2里
self.queue1, self.queue2 = self.queue2, self.queue1#交换队列1 和2 的值
def pop(self) -> int:
"""Removes the element on top of the stack and returns that element."""
return self.queue1.popleft()#此时的队列1相当于栈
def top(self) -> int:
""" Get the top element."""
return self.queue1[0]
def empty(self) -> bool:
"""Returns whether the stack is empty."""
return not self.queue1
LC622设计循环队列(数组O(1)、O(N))*
def __init__(self, k: int):
"""构造器,设置队列长度为 k """
self.queue = [0]*k#一个固定大小的数组,用于保存循环队列的元素。
self.headIndex = 0#一个整数,保存队首 head 的索引
self.count = 0#循环队列当前的长度,即循环队列中的元素数量
self.capacity = k#循环队列的容量,即队列中最多可以容纳的元素数量
def enQueue(self, value: int) -> bool:
"""向循环队列插入一个元素。如果成功插入则返回真"""
if self.count == self.capacity:
return False
#队尾新添元素的位置 tailInd=(headIndex+count) mod capacity
#队尾已有元素的位置 (headIndex+count-1) mod capacity
self.queue[(self.headIndex + self.count) % self.capacity] = value
self.count += 1
return True
def deQueue(self) -> bool:
"""从循环队列中删除一个元素。如果成功删除则返回真。"""
if self.count == 0:
return False
self.headIndex = (self.headIndex + 1) % self.capacity队首位置后移
self.count -= 1
return True
def Front(self) -> int:
"""从队首获取元素。如果队列为空,返回 -1 。"""
if self.count == 0:
return -1
return self.queue[self.headIndex]
def Rear(self) -> int:
"""获取队尾元素。如果队列为空,返回 -1 """
# empty queue
if self.count == 0:
return -1
return self.queue[(self.headIndex + self.count - 1) % self.capacity]
def isEmpty(self) -> bool:
"""检查循环队列是否为空。"""
return self.count == 0#len(self.q)==0不可以
def isFull(self) -> bool:
"""检查循环队列是否已满。"""
return self.count == self.capacity
LC641 设计循环双端队列(确定队列头指针和队列尾指针的位置)*
def __init__(self, k: int):
"""构造函数,双端队列的大小为k"""
self.capacity = k + 1
self.deque = [0 for _ in range(self.capacity)]
self.front = 0#指向队列头部第 11 个有效数据的位置;
self.rear = 0#指向队列尾部(即最后 11 个有效数据)的下一个位置,即下一个从队尾入队元素的位置
def insertFront(self, value: int) -> bool:
"""将一个元素添加到双端队列头部。 如果操作成功返回 true"""
if not self.isFull():
#front先减一 再赋值
self.front = (self.front - 1) % self.capacity
self.deque[self.front] = value
return True
return False
def insertLast(self, value: int) -> bool:
"""将一个元素添加到双端队列尾部。如果操作成功返回 true"""
if not self.isFull():
self.deque[self.rear] = value#先赋值 rear再加一
self.rear = (self.rear + 1) % self.capacity
return True
return False
def deleteFront(self) -> bool:
"""从双端队列头部删除一个元素。 如果操作成功返回 true"""
if not self.isEmpty():
#front右移一格,即下标加一 再取模?
self.front = (self.front + 1) % self.capacity
return True
return False
def deleteLast(self) -> bool:
"""从双端队列尾部删除一个元素。如果操作成功返回 true"""
if not self.isEmpty():#near左移一格 取模?
self.rear = (self.rear - 1) % self.capacity
return True
return False
def getFront(self) -> int:
"""从双端队列头部获得一个元素。如果双端队列为空,返回 -1"""
if not self.isEmpty():
return self.deque[self.front]
return -1
def getRear(self) -> int:
"""获得双端队列的最后一个元素。 如果双端队列为空,返回 -1"""
if not self.isEmpty():
return self.deque[self.rear - 1]
return -1
def isEmpty(self) -> bool:
"""检查双端队列是否为空。"""
if self.front == self.rear:#front=rear
return True
return False
def isFull(self) -> bool:
"""检查双端队列是否满了"""
if (self.rear + 1)== self