码迷,mamicode.com
首页 > 其他好文 > 详细

378. Kth Smallest Element in a Sorted Matrix

时间:2017-06-22 00:16:28      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:for   turn   key   else   最小值   ==   sorted   注意   public   

https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/#/solutions

http://www.cnblogs.com/EdwardLiu/p/6109080.html

Heap :

public class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        int n = matrix.length;
        PriorityQueue<Tuple> pq = new PriorityQueue<Tuple>(); // 类继承了 Comparable 后直接()构造, 与landly的comparator方法作比较
        for(int j = 0; j <= n-1; j++) pq.offer(new Tuple(0, j, matrix[0][j]));
        for(int i = 0; i < k-1; i++) {
            Tuple t = pq.poll();
            if(t.x == n-1) continue;
            pq.offer(new Tuple(t.x+1, t.y, matrix[t.x+1][t.y]));
        }
        return pq.poll().val;
    }
}

class Tuple implements Comparable<Tuple> {
    int x, y, val;
    public Tuple (int x, int y, int val) {
        this.x = x;
        this.y = y;
        this.val = val;
    }
    
    @Override
    public int compareTo (Tuple that) {
        return this.val - that.val;
    }
}

  

Solution 2 : Binary Search
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"

  1. index -- A bunch of examples -- https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ ( the array is sorted)
  2. 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.

public int kthSmallest(int[][] matrix, int k) {
        int lo = matrix[0][0], hi = matrix[matrix.length - 1][matrix[0].length - 1] + 1;//[lo, hi)
        while(lo < hi) {
            int mid = lo + (hi - lo) / 2;
            int count = 0,  j = matrix[0].length - 1;       //O(nlgX),其中X为最大值和最小值的差值,我们并不用对每一行都做二分搜索法,
                                  我们注意到每列也是有序的,我们可以利用这个性质,
从数组的左下角开始查找,如果比目标值小,我们就向右移一位,
     而且我们知道当前列的当前位置的上面所有的数字都小于目标值,
那么cnt += i+1,反之则向上移一位,这样我们也能算出cnt的值。 for(int i = 0; i < matrix.length; i++) { while(j >= 0 && matrix[i][j] > mid) j--; count += (j + 1); } if(count < k) lo = mid + 1; else hi = mid; } return lo; }

  

378. Kth Smallest Element in a Sorted Matrix

标签:for   turn   key   else   最小值   ==   sorted   注意   public   

原文地址:http://www.cnblogs.com/apanda009/p/7062064.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!