LeetCode378题:有序矩阵中第k小的元素

思路:

首先分析已知条件,即数组是每行从左到右递增,每列从上到下递增的(非严格递增)。要找到第k小的元素,那么最笨的方法就是将数组所有元素升序排序后,取第k个元素;或者是用优先级队列的思想,始终维持已遍历元素中的k个最小元素,直到遍历结束,取队列的最后一个元素;或者用小顶堆的数据结构,遍历数组并构建堆,构建完成后,找到第k小的元素。

解法一:排序(最笨的) 

public int kthSmallest(int[][] matrix, int k) {
        int row = matrix.length;
        int col = matrix[0].length;
        int[] arr = new int[row*col+1];
        arr[0] = matrix[0][0];
        int index = 0;
        for(int i=0;i<row;i++){
            for(int j=0;j<col;j++){
                int temp = index;
                while(matrix[i][j] < arr[temp]){
                    arr[temp+1] = arr[temp];
                    temp--;
                }
                arr[temp+1] = matrix[i][j];
                index++; 
            }
        }
        return arr[k];
    }

这种方法时间复杂度太大,执行时间达到560ms,只能击败0.69%的提交记录。使用的是插入排序的思想,之所以时间复杂度高,一个可能的原因应该是使用了数组作为保存排序结果的数据结构,这就回导致多次的复制操作,如果换成链表应该会好一些。(注意,因为数组存在相同的数,因此不能使用TreeSet)。

链表结构实现排序

public int kthSmallest(int[][] matrix, int k) {
        int row = matrix.length;
        int col = matrix[0].length;
        ArrayList<Integer> list = new ArrayList<Integer>();
        for(int i=0;i<row;i++){
            for(int j=0;j<col;j++){
               list.add(matrix[i][j]);  
            }
        }
        Collections.sort(list);
        return list.get(k-1);
    }

果然这种数据结构要比数组的时间复杂度低,平均只要55ms,但也只能击败20%左右的提交记录。 

解法二:小顶堆

class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        int n = matrix.length;
        PriorityQueue<Tuple> pq = new PriorityQueue<Tuple>();
        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;
    }
}

解法三:二分查找

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;
            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;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值