示例#1
0
def heapq_sample():
    heap=[]
    original_items=[1,6,3,5,2,7,4,2,5,6,3,2]
    for i in original_items:
        heapq.heappush(heap,i)
    # 按照从小到达的顺序进行pop
    for _ in original_items:
        print heapq.heappop(heap)
示例#2
0
 def topKFrequent2(self, nums: List[int], k: int) -> List[int]:
     counter = Counter(nums)
     pq = []
     for key in counter:
         if len(pq) < k:
             _heapq.heappush(pq, [counter[key], key])
         elif counter[key] > pq[0][0]:
             _heapq.heapreplace(pq, [counter[key], key])
     return [key for _, key in pq]
示例#3
0
def middle_heapq(heap, middle):
    temp_heap = []
    for num in heap:
        _heapq.heappush(temp_heap, num)

    middle_num = 0
    for _ in range(middle):
        middle_num = _heapq.heappop(temp_heap)

    return middle_num
def merge(lists):
    merged_list = []

    heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst]

    # basically sorting the array of tuple
    _heapq.heapify(heap)

    while heap:
        val, list_ind, element_ind = _heapq.heappop(heap)
        merged_list.append(val)

        if element_ind + 1 < len(lists[list_ind]):
            next_tuple = (lists[list_ind][element_ind + 1], list_ind,
                          element_ind + 1)
            _heapq.heappush(heap, next_tuple)
    return merged_list
示例#5
0
def findKthLargest(self, nums: List[int], k: int) -> int:
    """
    Time Complexity: O(N.Log(N)) height of tree traverse *  creating heap
    Space Complexity: O(N)
    Accepted
    Using heapq library, we can utilize nlargest method _heapq.nlargest(k, nums) as well.
    """

    result = []
    #base case
    if not nums or not k or k < 0:
        return None

    for i in nums:
        if len(result) > k and i > result[0]:
            _heapq.heapreplace(result, i)
        else:
            _heapq.heappush(result, i)
    return result
示例#6
0
def solve(adj, K):
    prev = [-1] * (len(adj) + 1)
    dist = [INF] * (len(adj) + 1)
    dist[K] = 0

    priority_queue = []
    _heapq.heappush(priority_queue,[0, K])

    while priority_queue:
        current_dist , here = _heapq.heappop(priority_queue)

        for there, length in adj[here].items():
            next_dist = dist[here] + length

            if(next_dist < dist[there]):
                dist[there] = next_dist
                prev[there] = here
                _heapq.heappush(priority_queue, [next_dist, there])
    
    return dist, prev
示例#7
0
 def minMeetingRooms(self, intervals):
     import collections
     from collections import _heapq
     """
     :type intervals: List[List[int]]
     :rtype: int
     """
     if len(intervals) == 0:
         return 0
     # As we deal with the intervals we need to sort them out based
     # on the start time
     intervals.sort(key = lambda x:x[0])
     # This is the priority queue
     free_rooms = []
     # We are filling the queue with the end interval times
     _heapq.heappush(free_rooms, intervals[0][1])
     for i in range(1, len(intervals)):
         # Check the earliest end time if the earliest end time
         # is less than the start time we should pop that interval
         if free_rooms[0] <= intervals[i][0]:
             _heapq.heappop(free_rooms)
         # Any ways you need to push the new end time to the heap
         _heapq.heappush(free_rooms, intervals[i][1])
     return len(free_rooms)
示例#8
0
import sys
from collections import _heapq

N = int(sys.stdin.readline())

heap = []

for _ in range(N):
    num = int(sys.stdin.readline())
    if (num == 0):
        if (len(heap) == 0):
            print(0)
        else:
            print(_heapq.heappop(heap))
    else:
        _heapq.heappush(heap, num)
示例#9
0
import sys
from collections import _heapq

heap = []
input = sys.stdin.readline

N = int(input())

for _ in range(N):
    num = int(input())

    if( num == 0 ):
        if(len(heap) > 0):
            result = _heapq.heappop(heap)
            print(result[0] * result[1])
        else:
            print(0)
    
    else:
        _heapq.heappush(heap, (abs(num), 1 if num > 0 else -1))
    
示例#10
0
import sys
from collections import _heapq

N = int(sys.stdin.readline())

heap = []

for _ in range(N):
    num = int(sys.stdin.readline())
    if (num != 0):
        _heapq.heappush(heap, (-num, num))
    else:  # num == 0
        if (len(heap) == 0):
            print(0)
        else:
            print(_heapq.heappop(heap)[1])
示例#11
0
from collections import _heapq
f = open("Median.txt", 'r')
Hlow = [] # support extract Max
Hhigh = []# support extract Max
Medians = []

for line in f:
    e = int(line)
    if len(Hlow) > 0:
        if -e > Hlow[0]:
            _heapq.heappush(Hlow, -e)
        else:
            _heapq.heappush(Hhigh, e)
    else:
        _heapq.heappush(Hlow, -e)

    if len(Hlow) > len(Hhigh) + 1:
        f = _heapq.heappop(Hlow)
        _heapq.heappush(Hhigh, -f)
    elif len(Hhigh) > len(Hlow) + 1:
        f = _heapq.heappop(Hhigh)
        _heapq.heappush(Hlow, -f)

    if len(Hlow) > len(Hhigh) or len(Hlow) == len(Hhigh):
        Medians.append(-Hlow[0])
    elif len(Hhigh) > len(Hlow):
        Medians.append(Hhigh[0])

print(len(Medians))
print(sum(Medians))
print(sum(Medians) % 10000)
示例#12
0
if key not in status:
    status[key] = 0
status[key] += 1
print status

status = {}
status[key] = status.setdefault(key, 0) + 1
print status

from collections import defaultdict
status = defaultdict(int)
status[key] += 1
print status

print "============="

from collections import _heapq
a = []
_heapq.heappush(a, 5)
_heapq.heappush(a, 3)
_heapq.heappush(a, 7)
_heapq.heappush(a, 4)
print a

print "============="

import bisect
a = list(range(100))
i = bisect.bisect_left(a, 98)
print i
示例#13
0
from collections import _heapq

f = open("Median.txt", 'r')
Hlow = []  # support extract Max
Hhigh = []  # support extract Max
Medians = []

for line in f:
    e = int(line)
    if len(Hlow) > 0:
        if -e > Hlow[0]:
            _heapq.heappush(Hlow, -e)
        else:
            _heapq.heappush(Hhigh, e)
    else:
        _heapq.heappush(Hlow, -e)

    if len(Hlow) > len(Hhigh) + 1:
        f = _heapq.heappop(Hlow)
        _heapq.heappush(Hhigh, -f)
    elif len(Hhigh) > len(Hlow) + 1:
        f = _heapq.heappop(Hhigh)
        _heapq.heappush(Hlow, -f)

    if len(Hlow) > len(Hhigh) or len(Hlow) == len(Hhigh):
        Medians.append(-Hlow[0])
    elif len(Hhigh) > len(Hlow):
        Medians.append(Hhigh[0])

print(len(Medians))
print(sum(Medians))