leetcode 378

有序矩阵中第K小的元素

Posted by Static on July 2, 2020

题目链接:https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix/

题目描述


分析

1. 添加到数组中,再排序取值


代码实现

public enum Q378 {
    instance;
    public int kthSmallest(int[][] matrix, int k) {
        List<Integer> list=new ArrayList<>();
        for(int[] array:matrix){
            for(int num:array){
                list.add(num);
            }
        }
        Object[] objects = list.toArray();
        Arrays.sort(objects);
        return (int) objects[k-1];
    }

    public static void main(String[] args) {
        int[] a={1,  5,  9};
        int[] b={10, 11, 13};
        int[] c={12, 13, 15};
        int[][] matrix=new int[][]{a,b,c};
        // assert 13
        System.out.println(Q378.instance.kthSmallest(matrix,8));
    }
}

No matter where a noble man goes,he is always accompanied by a firm guard–conscience. (Britain) Scott

高尚的人无论走向何处,身边总有一个坚强的捍卫者–那就是良心 – [英] 斯科特