记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步
703.kth-largest-element-in-a-stream 数据流中的第K大元素
解题思路:在heap中保留k个数 来一个新的数时与heap中的第一个数 及第K大元素的数比较
import heapq
class KthLargest(object):
def __init__(self, k, nums):
"""
:type k: int
:type nums: List[int]
"""
self.nums = nums
self.size = len(self.nums)
self.k = k
heapq.heapify(self.nums)
while self.size > k:
heapq.heappop(self.nums)
self.size -= 1
def add(self,val):
"""
:type val: int
:rtype: 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]
743.network-delay-time 网络延迟时间
解题思路:
def networkDelayTime(times, N, K):
"""
:type times: List[List[int]]
:type N: int
:type K: int
:rtype: int
"""
INF = 0x7FFFFFFF
gradic = {}
resdic = {}
for i in range(len(times)):
u,v,w = times[i]
ul = gradic.get(u,[])
ul.append((v,w))
gradic[u] = ul[:]
line = [K]
resdic[K]=0
while line:
k = line.pop()
tmppath = resdic[k]
tmpl = gradic.get(k,[])
for tv,tw in tmpl:
imapath = resdic.get(tv,INF)
if tw+tmppath < imapath:
resdic[tv]=tw+tmppath
line.append(tv)
if len(resdic)<N:
return -1
return max(resdic.values())