378. Kth Smallest Element in a Sorted Matrix
2016-12-03 17:46
369 查看
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:
分析:二分搜索。通过值来实现二分搜索。
Note:
You may assume k is always valid, 1 ≤ k ≤ n2.
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.
public class Solution { public int kthSmallest(int[][] matrix, int k) { int m=matrix.length-1; int n=matrix[0].length-1; int l_v=matrix[0][0]; int h_v=matrix[m] ; int count; int mid; int j; while(l_v<h_v){ mid=l_v+(h_v-l_v)/2; count=0; for(int i=0;i<=m;i++){ j=n; while(j>=0&&matrix[i][j]>mid) j--; count+=j+1; } if(count>=k) h_v=mid; else l_v=mid+1; } return l_v; } }
相关文章推荐
- 几个最常用的git命令
- Redis 数据类型
- web前端之dojo实际应用及开发六:页面布局(附有源码)
- POJ 1047 Round and Round We Go 已被翻译
- CVPR2016代码&文章
- java之内部类详解
- 让返回键不能用
- 关于hibernate 持久化中遇到的detached entity passed to persist异常解决
- 烈焰部分数据库表注释说明
- 什么是野指针?野指针的危害?如何避免野指针?
- 微机个人笔记-存储单元编址
- 8种排序算法及性能特点
- VS使用WinRAR软件以命令行方式打包软件至一个exe
- init.rc中的mount等命令执行时调用的源码位置
- Java 并发专题:Timer的缺陷用ScheduledExecutorService替代
- MySQL主从复制搭建教程
- 计算机体系架构
- 哈尔滨理工大学软件学院ACM程序设计全国邀请赛(水题5道)
- 显示系统信息与硬件信息的bat代码
- JAVA学习之-数据库设计及优化_课堂笔记