LeetCode 264.丑数
在做这个题目之前我们先自己造个轮子——实现一个堆
维护堆的性质
def max_heapify(A,i):
left = 2*i+1
right = 2*i+2
max = i
if left < len(A) and A[left]> A[i]:
max = left
if right < len(A) and A[right] > A[max]:
max = right
if max != i:
A[i], A[max] = A[max], A[i]
A = max_heapify(A, max)
return A
A = [16,4,10,14,7,9,3,2,8,1]
print(max_heapify(A,1))
[16, 14, 10, 8, 7, 9, 3, 2, 4, 1]
堆的建立
def build_heap(A):
heap_size = len(A)
for i in range(heap_size//2,-1,-1):
A = max_heapify(A, i)
return A
build_heap([1,4,2,3,7,9,8,16,14,10])
[16, 14, 9, 4, 10, 2, 8, 3, 1, 7]
堆排序
def heap_sort(A):
B = []
A = build_heap(A)
for i in range(len(A)-1,0,-1):
A[i], A[0] = A[0], A[i]
B.append(A.pop(-1))
max_heapify(A, 1)
return B
heap_sort([6,7,2,5,4,2,3])
[7, 2, 2, 4, 5, 3]
LeetCode 264.丑数
动态规划求解
def nthUglyNumber(n) -> int:
dp = [1]
i2, i3, i5 = 0, 0, 0
while n > 1:
dp.append(min(2*dp[i2], 3*dp[i3], 5*dp[i5]))
if dp[-1]>= dp[i2]*2 : i2 += 1
if dp[-1]>= dp[i3]*3 : i3 += 1
if dp[-1]>= dp[i5]*5 : i5 += 1
n = n - 1
return dp[-1]
优先队列求解
import heapq
def nthUglyNumber(n) -> int:
heap = [1]
heapq.heapify(heap)
while n > 0:
res = heapq.heappop(heap)
while heap and res == heap[0]:
res = heapq.heappop(heap)
for i in [2,3,5]:
heapq.heappush(heap,i*res)
n = n - 1
return res
欢迎关注公众号 : 数学算法实验室