1. 程式人生 > >LeetCode-堆-Easy

LeetCode-堆-Easy

記錄了初步解題思路 以及本地實現程式碼;並不一定為最優 也希望大家能一起探討 一起進步


目錄



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())