Heap related topics -python

Stack & heap queue & hash table & -python   https://blog.csdn.net/qq_19446965/article/details/102982047

1, the number of ugly II 

Write a program to find the n-th ugly numbers.

Ugly contains only the number of prime factors is a positive integer of 2, 3, 5.

Example:

Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is a front number 10 ugly.
Description:  

1 is the number of ugly.
n is not more than 1,690.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/ugly-number-ii

First recall the "ugly number I"

Write a program to determine whether a given number is a number of ugly.

https://leetcode-cn.com/problems/ugly-number-ii/

class Solution(object):
    def isUgly(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num <= 0:
            return False
        if num == 1:
            return True  
          
        while num >= 2 and num % 2 == 0:
            num /= 2
        while num >= 3 and num % 3 == 0:
            num /= 3 
        while num >= 5 and num % 5 == 0:
            num /= 5
          
        return num == 1

  

Opposite number a little ugly II

class Solution(object):
    def nthUglyNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        import heapq
        heap = [1]
        visited = set([1])
        
        num = None
        for i in range(n):
            num = heapq.heappop(heap)
            for factor in [2, 3, 5]:
                if num * factor not in visited:
                    visited.add(num * factor)
                    heapq.heappush(heap, num * factor)
            
        return num

 

2、Top k largest Number 

Example: n-th value selected maximum number k (3 <k <n) is the minimum algorithm complexity (O (n))

1. The easiest way: The number n of ordered, sorted before k is the maximum number of the number k, the complexity of this algorithm is O (nlogn)

2.O (n) method:

Solution 1: using patition thought fast row from the array S to find a random element X, the array is divided into two portions Sa and Sb. Sa is greater than or equal elements X, Sb elements is less than X. Then there are two cases:

      1. Sa number of elements is less than k, then the first k- Sb | Sa | is the k-th element of large numbers;

      2. Sa number of elements greater than or equal k, Sa k-th large number is returned. Approximate time complexity O (n), but the worst case complexity of O (n ^ 2).

Solution 2: using array element number stored hash Si appears by counting thought sorted, in descending linear scanning process, the number in front of the k-k-1, compared with large numbers, times the average case complexity O (n)

3.O (nlogk) method: create a minimum size for the heap of k, then every time we read a number from the n integer input, if the number of the top of the heap than the minimum stack elements bigger, then replace the top of the heap and stack the smallest adjustment.

Advantages and disadvantages of the two methods:

Heapsort suitable for mass data that it does not need all the data is loaded into memory, only you need to maintain a small size of the top of the heap m, which is one of its great advantages.

Fast discharge method is fast, but the face of massive data becomes helpless, because he needs to maintain the entire array.

4..O (n) finds the first K small number BFPRT algorithm - warm3snow - blog https://www.cnblogs.com/informatics/p/5092741.html Park

The main idea is to modify the unit selection method for rapid selection algorithm and improve the time complexity of the algorithm in the worst case. The main steps are:

  1. First, the array grouped according to the number 5 as a group, less than five of the last ignore. Sorting each group number (e.g., insertion sort) wherein the number of bits is obtained.
  2. The last step in the median all moved to the front of the array, the median of these recursive calls BFPRT algorithm to obtain their median.
  3. The median of the previous step was used as a primary division element divides the entire array.
  4. Determination of the number k of the division result to the left, right or the result itself happens to be divided, the first two recursive processing, which direct the return key.

 

Its budget law will not be realized, this only concerns heap

class Solution:
    def get_top_k(k, nums):
        import heapq
        heap = []
        for num in nums:
            heapq.heappush(heap, num)
            if len(heap) > k:
                heapq.heappop(heap)

        return sorted(heap, reverse=True)

3, k merge sort list

K merge sort list, and returns a list sorted combined. Try to analyze and describe its complexity.

class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next

Method One: Merging Algorithm

 

class Solution:
    """
    @param lists: a list of ListNode
    @return: The head of one sorted list.
    """
    def mergeKLists(self, lists):
        if not lists:
            return None
        
        return self.merge_range_lists(lists, 0, len(lists) - 1)
        
    def merge_range_lists(self, lists, start, end):
        if start == end:
            return lists[start]
        
        mid = (start + end) // 2
        left = self.merge_range_lists(lists, start, mid)
        right = self.merge_range_lists(lists, mid + 1, end)
        return self.merge_two_lists(left, right)
        
    def merge_two_lists(self, head1, head2):
        tail = dummy = ListNode(0)
        while head1 and head2:
            if head1.val < head2.val:
                tail.next = head1
                head1 = head1.next
            else:
                tail.next = head2
                head2 = head2.next
            tail = tail.next
            
        if head1:
            tail.next = head1
        if head2:
            tail.next = head2
        
        return dummy.next

 

  

 

Method Two: Use heap

1, all the elements are added to the stack 
2, traversal, a remove a minimum, connected

 

heapq Import 
ListNode .__ lt__ the lambda = X, Y: (x.val <y.val) 

class Solution: 
    "" " 
    @param Lists: A List of ListNode 
    @return:. One of The head of the sorted List 
    " "" 
    DEF mergeKLists ( Self, Lists): 
        IF Not Lists: 
            return None 
        
        dummy = ListNode (0) 
        tail dummy = 
        heap = [] 
        for head in Lists: #. 1, all the stack elements to 
            IF head: 
                heapq.heappush (heap, head) 
                
        the while heap: # 2, traverse, a remove a minimum connecting 
            head = heapq.heappop (heap) 
            tail.next = head  
            tail = head
            IF head.next:
                heapq.heappush(heap, head.next)
                    
        return dummy.next

 

  

 

———————————————————

 Reference: IX algorithm explain  https://www.jiuzhang.com/solution/

 

Guess you like

Origin www.cnblogs.com/rnanprince/p/11879690.html