标签:
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小项,但是这样处理的话没有体现出原多维数组的有序性。笔者目前也刚处于学习阶段,更好的解法于日后补上。
解法:
设立一维数组储存所有元素,排序后返回第k小项。
1 import java.util.Arrays; 2 import java.util.ArrayList; 3 4 public class Solution 5 { 6 public int kthSmallest(int[][] matrix, int k) 7 { 8 ArrayList<Integer> list = new ArrayList<>(); 9 10 for(int[] smallMatrix: matrix) 11 for(int i: smallMatrix) 12 list.add(i); 13 14 int[] array = new int[list.size()]; 15 16 for(int i = 0; i < list.size(); i++) 17 array[i] = list.get(i); 18 19 Arrays.sort(array); 20 21 return array[k - 1]; 22 } 23 }
LeetCode 378 Kth Smallest Element in a Sorted Matrix
标签:
原文地址:http://www.cnblogs.com/wood-python/p/5732087.html