Ejemplo n.º 1
0
 def largestSumAfterKNegations(self, A: List[int], K: int) -> int:
     _sum = sum(A)
     heapq.heapify(A)
     while K > 0:
         curmin = heapq.heappop(A)
         heapq.heappush(A, -curmin)
         K -= 1
         _sum += -curmin * 2
     return _sum
 def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
     hp = [(node.val, i, node) for i, node in enumerate(lists) if node]
     heapq.heapify(hp)
     counter = len(lists)
     dummy_head = curr = ListNode()
     while hp:
         _, _, node = heapq.heappop(hp)
         curr.next = node
         if node.next:
             heapq.heappush(hp, (node.next.val, counter, node.next))
             counter += 1
         curr = curr.next
     return dummy_head.next
Ejemplo n.º 3
0
    def reorganizeString2(self, S):
        pq = [(-S.count(x), x) for x in set(S)]
        heapq.heapify(pg)
        if any(-ct > (len(s) + 1) / 2 for ct, x in pg):
            return ""

        ans = []
        while len(pq) >= 2:
            freq1, ch1 = heapq.heappop(pq)
            freq2, ch2 = heapq.heappop(pq)
            #This code turns out to be superfluous, but explains what is happening
            #if not ans or ch1 != ans[-1]:
            #    ans.extend([ch1, ch2])
            #else:
            #    ans.extend([ch2, ch1])
            ans.extend([ch1, ch2])
            if freq1 + 1:  # notice the freq is negative here...
                heapq.heappush(pq, (freq1 + 1, ch1))
            if freq2 + 1:
                heapq.heappush(pq, (freq2 + 1, ch2))

        # second part is for single pair left in the heapq
        return "".join(ans) + (pq[0][1] if pq else '')
Ejemplo n.º 4
0
class Solution:
	# maintain the heap
	# T: O(clogN), N as number of employees, C the number of all intervals/jobs
    # O(logN) for push and pop in heap of size N
    # O(c) as number of such operations
	def employeeFreeTime3(self, schedule: '[[Interval]]') -> '[Interval]':
		ans = []
		# (job_idx_th start time, user ID, job idx)
        pq = [(emp[0].start, empID, 0) for empID, emp in enumerate(schedule)]
        heapq.heapify(pq)
        # anchor: minimal start time for all employee
        prev_end = pq[0][0] # start time!
        while pq: # e_id: employee id; cur_jobId: current job ID
            start_time, e_id, cur_jobId = heapq.heappop(pq)
            # no overlap
            if start_time > prev_end:
                ans.append(Interval(prev_end, start_time))
            # overlap, update prev_end
            prev_end = max(prev_end, schedule[e_id][cur_jobId].end)
           	# # if there are more intervals available for the same employee, add their next interval
            if cur_jobId + 1 < len(schedule[e_id]): # push next job into it
                heapq.heappush(pq, (schedule[e_id][cur_jobId+1].start, e_id, cur_jobId+1))

        return ans



	# minheap, still not optimal since all intervals in heap
	# T: O(clogc), N as number of employees, C the number of all intervals
	# S: O(N)
	def employeeFreeTime2(self, schedule: '[[Interval]]') -> '[Interval]':
		res = []
        intervals = [(i.start, i.end) for emp in schedule for i in emp]
        heapify(intervals)

        start, end = heappop(intervals)
        prev_end = end
        while intervals:
            cur_start, cur_end = heappop(intervals)
            if cur_start > prev_end:
                res.append(Interval(prev_end, cur_start))
                prev_end = cur_end
            else:
                prev_end = max(cur_end, prev_end)
        return res



	# T: O(clogc), n as number of all intervals, not optimal
	def employeeFreeTime1(self, schedule: '[[Interval]]') -> '[Interval]':
		intervals = sorted([i for emp in schedule for i in emp], \
			key=lambda x: x.start)
	    res, pre = [], intervals[0]
	    for cur_interval in intervals[1:]:
	    	# overlap, extend/update the prev_end
	        if cur_interval.start <= pre.end and cur_interval.end > pre.end:
	            pre.end = cur_interval.end
	        # no overlap
	        elif cur_interval.start > pre.end:
	            res.append(Interval(pre.end, cur_interval.start))
	            pre = cur_interval
	    return res
 def sortArray(self, nums):
     sorted_list=[]
     heapq.heapify(nums)
     return [(heapq.heappop(nums)) for i in range(len(nums))]