Kth Smallest Element in a Sorted Matrix-LeetCode#378

378. Kth Smallest Element in a Sorted Matrix

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.
矩阵中第K小的元素

给定n×n矩阵,其中每个行和列按升序排序,找到矩阵中的第k个最小元素。

它是排序顺序中的第k个最小元素,而不是第k个不同元素。
思路:循环遍历每个元素后,添加到一个 List ,使用 Collections.sort() 方法,排序后取 K – 1 位

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

 

文章已创建 112

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部