Leetcode 378. Kth smallest Element in a Sorted Matrix

Source: Internet
Author: User

Given a n x n Matrix where each of the rows and columns is sorted in ascending order, find the kth smal Lest element in the matrix.

Note that it was the kth smallest element in the sorted order and not the kth distinct element.

Example:

Matrix = [   [1,  5,  9],   [Ten, one, +],   [15]],k = 8,return 13.

The solution of the subject is exactly similar to the find K pairs with smallest sums. In that problem, every time (A1,BK) is less than the top element of the heap, we push all the (A1,BK),..., (AN,BK) into the heap. Then idx2 + = 1. We do similar things here, and whenever Matrix[row][0] is smaller than the top element of the heap, we push the entire line into the heap. It is important to note that the heap needs to be stored in a maxint, otherwise the pop empty heap may occur.

1 classsolution (object):2     defkthsmallest (self, Matrix, K):3         """4 : Type Matrix:list[list[int]]5 : Type K:int6 : Rtype:int7         """8Ans = []9heap = [(0x7FFFFFFF, none, none)]TenSize1, size2 =len (Matrix), Len (matrix[0]) Onerow =0 A          whileLen (ANS) <K: -             ifRow <size1: -                 ifMatrix[row][0] <Heap[0]: the                      forColinchRange (size2): - Heapq.heappush (Heap, Matrix[row][col]) -Row + = 1 -val =heapq.heappop (Heap) + Ans.append (val) -         returnANS[K-1]

In fact, due to the special structure of the matrix, the smallest element is definitely matrix[0][0], we just need to maintain a heap, each pop out of the heap top element, the smallest two elements greater than his ([Row, col+1] and [Row+1, Col]) pushed into the heap. When the Heappop executes the K-th, the value of the pop is the small element of the k in the matrix. There is a need to maintain a visited matrix to record whether a node has been pushed into the heap. Otherwise, a point is pushed into the heap multiple times.

1 classsolution (object):2     defkthsmallest (self, Matrix, K):3         """4 : Type Matrix:list[list[int]]5 : Type K:int6 : Rtype:int7         """8M, n =len (Matrix), Len (matrix[0])9Heap =[(Matrix[0][0], 0, 0)]Tenvisited = [[false]*n for_inchrange (m)] One  A          forIinchRange (k): -Val, row, col =Heap[0] -Visited[row][col] =True the             ifCol < n-1 andVISITED[ROW][COL+1] = =False: -VISITED[ROW][COL+1] =True -Heapq.heappush (Heap, (matrix[row][col+1], row, col+1)) -             ifRow < M-1 andVisited[row+1][col] = =False: +Visited[row+1][col] =True -Heapq.heappush (Heap, (Matrix[row+1][col], row+1, col)) +Ans, row, col =heapq.heappop (Heap) A          at         returnAns

Solution Three, dichotomy search binary search

The upper left corner of the element low = Matrix[0][0], and the lower right corner of the element high = Matrix[-1][-1] is clearly the smallest and largest. We can find out how many elements are less than or equal to Mid = (low + high)//2.

Consider the following example: Low = 1, high = $, MID = 11

Looking from the lower left corner, if matrix[i][j] > Mid, then the element on the right side is definitely larger than mid. We'll look at the previous line (i--), if MATIX[I][J] <= mid, then it's itself and the elements above it <=mid. So cnt + = (i+1), and J + +. The boundary condition is (i>=0, j<=n-1). In the figure, the number of elements less than or equal to mid is 4+4+2+2+2= 14.

To make it easier for us to write the K element as L. If 14<k, then mid=11 than L to be strictly small, you can set low = Mid+1. Conversely, mid>= L can be set to High = mid.

1     defkthsmallest (self, Matrix, K):2         """3 : Type Matrix:list[list[int]]4 : Type K:int5 : Rtype:int6         """7n =len (Matrix)8Low, High = matrix[0][0], matrix[-1][-1]9          whileLow <High :TenMid = (low + high) >>1 Onetemp =self.search_lower_than_mid (Matrix, N, mid) A             ifTemp <K: -Low = mid + 1 -             Else: theHigh =Mid -         return Low -          -     defsearch_lower_than_mid (self, matrix, N, x): +I, j = n-1, 0 -CNT =0 +          whileI >= 0 andJ <N: A             ifMATRIX[I][J] >x: atI-= 1 -             Else: -J + = 1 -CNT + = I+1 -         returnCnt

Note L9 in the code, you cannot use low <= high. In this case, when the last high = low, the program will die loop. L16 return low or return high is available.

Leetcode 378. Kth smallest Element in a Sorted Matrix

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.