leetcode刷题笔记-heap

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Sengo_GWU/article/details/82490880

378. Kth Smallest Element in a Sorted Matrix

 我第一个想法是Heap,最小堆解,但是不会写,因为heap用得太少了,库都不熟悉。

此题还有binary search的解法,速度更快,时间复杂度更低。

heap:  堆排序时间复杂度是nlogn,插入是logn

  • insert an element into heap: O(log(n)), where n is the width of the matrix
  • find k the k-th element O(k)
  • Overall: O(klog(n))
class Solution(object):
    def kthSmallest(self, matrix, k):
        """
        :type matrix: List[List[int]]
        :type k: int
        :rtype: int
        """
        h = [(row[0], row, 1) for row in matrix]
        heapq.heapify(h)
        for i in xrange(k-1):
            num, row, index = h[0]
            if index < len(matrix[0]):
                heapq.heapreplace(h, (row[index], row, index+1))
            else:
                heapq.heappop(h)
        return h[0][0]

binary search:

  1. Since we are given 1 <= k <= n^2, the kth number must exist in [lo, hi] range.
  2. We use binary search to find the minimum number A, such that the count of ( numbers satisfying num <= A ) is >= k.
  3. The time complexity is O(n * log(n) * log(N)), where N is the search space that ranges from the smallest element to the biggest element. You can argue that int implies N = 2^32, so log(N) is constant. In a way, this is an O(n * log(n)) solution.

好好好,good good good ,this is the first time that I know we can use binary search on such a nxm matrix.

class Solution(object):
    def kthSmallest(self, matrix, k):
        """
        :type matrix: List[List[int]]
        :type k: int
        :rtype: int
        """
        low, high = matrix[0][0], matrix[-1][-1]
        
        while low < high:
            mid = (low + high) / 2
            
            count, j = 0, len(matrix[0]) - 1
            for i in xrange(len(matrix)):
                while j >= 0 and matrix[i][j] > mid:
                    j -= 1
                count += j + 1
            
            if count < k: low = mid + 1
            else: high = mid
        
        return low
            

猜你喜欢

转载自blog.csdn.net/Sengo_GWU/article/details/82490880