堆
(leetcode 703) 数据流中的第k大元素
利用小顶堆
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.k = k
self.size = len(nums)
self.nums = nums
heapq.heapify(self.nums)
while self.size > k:
heapq.heappop(self.nums)
self.size -= 1
def add(self, val: int) -> int:
if self.size < self.k:
heapq.heappush(self.nums,val)
self.size += 1
elif val > self.nums[0]:
heapq.heapreplace(self.nums,val)
return self.nums[0]
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
栈
- leetcode 20 有效的括号
class Solution:
def isValid(self, s: str) -> bool:
if not str:
return True
s_dict = {"(":")","{":"}","[":"]"}
que = []
for v in s:
if len(que) > 0:
if s_dict[que[-1]] == v:
que.pop()
else:
if v in s_dict.values():
return False
que.append(v)
else:
if v in s_dict.values():
return False
que.append(v)
if len(que) ==0:
return True
else:
return False
- (leetcode 155)最小栈
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.order = []
self.min = float('inf')
self.secMin = float('inf')
self.size = 0
def push(self, x: int) -> None:
self.stack.append(x)
self.size += 1
self.order = sorted(self.stack)
def pop(self) -> None:
if self.size == 0:
return None
indx = self.order.index(self.stack[-1])
del self.stack[-1]
del self.order[indx]
self.size -= 1
def top(self) -> int:
if self.size == 0:
return None
return self.stack[-1]
def getMin(self) -> int:
if self.size == 0:
return None
return self.order[0]
- (leetcode 225) 队列实现栈
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stacks = []
self.size = 0
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.stacks.append(x)
self.size += 1
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
re = self.stacks[-1]
del self.stacks[-1]
self.size -= 1
return re
def top(self) -> int:
"""
Get the top element.
"""
return self.stacks[-1]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
if self.size == 0:
return True
return False
- (leetcode 496) 下一个更大的元素
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
result = []
for v in nums1:
flag = 0
indx = nums2.index(v)
for m in nums2[indx:]:
if m > v:
result.append(m)
flag = 1
break
if not flag:
result.append(-1)
return result
(leetcode 682) 棒球比赛
注:题目,思路都很简单,注意要把字符变成数字
class Solution:
def calPoints(self, ops: List[str]) -> int:
que = []
for v in ops:
if v == "C":
if len(que) > 0:
que.pop()
else:
if v != "+" and v!= "D":
que.append(int(v))
else:
que.append(v)
for i,v in enumerate(que):
if v == "+":
if i == 0:
que[i] = 0
else:
tmp = i-2 if i >2 else 0
que[i] = sum(que[tmp:i])
elif v == "D":
if i>0:
que[i] = 2* que[i-1]
else:
que[i] = 0
sumr = 0
for v in que:
sumr += v
return sumr
- (leetcode 232) 用栈实现队列
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.que = []
self.size = 0
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.que.append(x)
self.size += 1
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
tmp = self.que[0]
del self.que[0]
self.size -= 1
return tmp
def peek(self) -> int:
"""
Get the front element.
"""
return self.que[0]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
if self.size ==0:
return True
return False
- (leetcode 884) 比较含退格的字符串
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
def delStr(s):
s1 = []
for v in s:
if v == "#":
if len(s1) > 0:
s1.pop()
else:
s1.append(v)
return s1
s1 = delStr(S)
t1 = delStr(T)
if s1 == t1:
return True
return False
贪心算法
- (leetcode 122) 买卖股票的最佳时机
class Solution:
def maxProfit(self, prices: List[int]) -> int:
sumr = 0
if len(prices) == 0:
return 0
for i in range(1,len(prices)):
tmp = prices[i] - prices[i-1]
if tmp > 0:
sumr += tmp
return sumr
- (leetcode 455) 分发饼干
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
def findIndex(val,indx):
flag = 0
for i in range(indx,len(orderS)):
if orderS[i] >= val:
return i
return len(orderS)
orderG = sorted(g)
orderS = sorted(s)
sumr = 0
indx = 0
for i in range(len(orderG)):
indx = findIndex(orderG[i],indx)
if indx< len(s):
sumr += 1
else:
break
indx += 1
return sumr
- (leetcode 860) 柠檬水找零
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
if not bills:
return True
changes = {5:0,10:0}
for v in bills:
if v == 5:
changes[5] += 1
elif v == 10:
if changes[5] == 0:
return False
else:
changes[5] -= 1
changes[10] += 1
else:
if changes[5] == 0:
return False
if changes[10] != 0:
changes[10] -= 1
changes[5] -= 1
else:
if changes[5] < 3:
return False
changes[5] -= 3
return True
(leetcode 136) 找出唯一的数
这道题的解法很精妙
class Solution:
def singleNumber(self, nums: List[int]) -> int:
if not nums:
return
tmp = nums[0]
for i in range(1,len(nums)):
tmp = tmp ^ nums[i]
return tmp
(leetcode 141) 环形链表
这题思路很精妙,使用快慢指针;如果有环一定能再次相遇
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
fast = low = head
while fast and fast.next:
fast = fast.next.next
low = low.next
if fast == low:
return True
return False