Skip to content

Latest commit

 

History

History
40 lines (31 loc) · 2.11 KB

378.md

File metadata and controls

40 lines (31 loc) · 2.11 KB

LeetCode 378 Kth Smallest Element in a Sorted Matrix——medium

Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
],
k = 8,

return 13.

Note: 
You may assume k is always valid, 1 ≤ k ≤ n2.

思路:
1、这里无法将索引和数字排序具体关联起来
2、所以直接将范围range定为搜索空间:即min——max、即 matrix[0][0]——matrix[n-1][n-1]
3、因为有重复数字,所以要计算的是小于等于mid的数量、如果count<k、则start = mid + 1
如果count >= k 、则end = mid ,这样子就可以让start逼近于end、
而end会在第k小的值这里等待start逼近

We are done here, but let's think about this problem in another way:
The key point for any binary search is to figure out the "Search Space". For me, I think there are two kind of "Search Space" -- index and range(the range from the smallest number to the biggest number). Most usually, when the array is sorted in one direction, we can use index as "search space", when the array is unsorted and we are going to find a specific number, we can use "range".
Let me give you two examples of these two "search space"
index -- A bunch of examples -- https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ ( the array is sorted)
range -- https://leetcode.com/problems/find-the-duplicate-number/ (Unsorted Array)
The reason why we did not use index as "search space" for this problem is the matrix is sorted in two directions, we can not find a linear way to map the number and its index.

To sum up, "lo" is ensured to reach an authentic element in the matrix, because "hi" will approach and sit at the right spot anyway.

Main loop is binary search of max - min.
Swap from left-bottom to right-top can get count <= mid in O(n) time instead of O(nlogn), total complexity will be O(nlogm) while m = max - min.