[Swift]LeetCode378. 有序矩阵中第K小的元素 | Kth Smallest Element in a Sorted Matrix

原文地址:https://www.cnblogs.com/strengthen/p/10280475.html 

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 ≤ n^2.


给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素。
请注意,它是排序后的第k小元素,而不是第k个元素。

示例:

matrix = [
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
],
k = 8,

返回 13。

说明: 
你可以假设 k 的值永远是有效的, 1 ≤ k ≤ n^2。


320ms

 1 class Solution {
 2     func kthSmallest(_ matrix: [[Int]], _ k: Int) -> Int {
 3         var matrix = matrix
 4         var left:Int = matrix[0][0]
 5         var right:Int = matrix.last!.last!
 6         while (left < right)
 7         {
 8             var mid:Int = left + (right - left) / 2
 9             var cnt:Int = search_less_equal(&matrix, mid)
10             if cnt < k
11             {
12                 left = mid + 1
13             }
14             else
15             {
16                 right = mid
17             }
18         }
19         return left
20     }
21     
22     func search_less_equal(_ matrix:inout [[Int]], _ target: Int) -> Int
23     {
24         var n:Int = matrix.count
25         var i:Int = n - 1
26         var j:Int = 0
27         var res:Int = 0
28         while(i >= 0 && j < n)
29         {
30             if matrix[i][j] <= target
31             {
32                 res += i + 1
33                 j += 1
34             }
35             else
36             {
37                 i -= 1
38             }
39         }
40         return res
41     }
42 }

384ms

 1 class Solution {
 2     func kthSmallest(_ matrix: [[Int]], _ k: Int) -> Int {
 3         var tagArr = [Int]();
 4         var totalItems = [Int]();
 5         for itmes in matrix {
 6             for item in itmes {
 7                 totalItems.append(item);
 8             }
 9         }
10         totalItems.sort();
11         var num = totalItems[k-1];
12         return num;
13     }
14 }

 

转载于:https://www.cnblogs.com/strengthen/p/10280475.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值