leetcode378
public class Solution {
public int KthSmallest(int[,] matrix, int k) {
var row = matrix.GetLength();
var col = matrix.GetLength();
var list = new List<int>();
for (int i = ; i < row; i++)
{
for (int j = ; j < col; j++)
{
list.Add(matrix[i, j]);
}
}
list = list.OrderBy(x => x).ToList();
return list[k - ];
}
}
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/#/description
补充一个多次使用二分查找的解决方案:
public class Solution {
public int KthSmallest(int[][] matrix, int k) {
int low = matrix[][];
int high = matrix[matrix.Length - ][matrix[].Length - ];
int count = ;
while (low <= high)
{
int mid = low + (high - low) / ;
count = GetCount(matrix, mid);
if (count < k)
{
low = mid + ;
}
else
{
high = mid - ;
}
}
return low;
}
private int GetCount(int[][] matrix, int num)
{
int ans = ;
int i = ;
int j = matrix[].Length - ;
while (i < matrix.Length && j >= )
{
if (matrix[i][j] > num)
{
j--;
}
else
{
ans += j + ;
i++;
}
}
return ans;
}
}
leetcode378的更多相关文章
- [Swift]LeetCode378. 有序矩阵中第K小的元素 | 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 ...
- leetcode378 Kth Smallest Element in a Sorted Matrix
思路1: 使用堆. 实现: class Solution { public: int kthSmallest(vector<vector<int>>& matrix, ...
- leetcode378 有序矩阵中第k小的元素
排序后取数组第k个元素,遍历需要n^2的复杂度,查找插入logn,时间复杂度O(n^2logn).方法很笨,完全就是STL过于牛x运行通过的. class Solution { public: int ...
- leetcode探索高级算法
C++版 数组和字符串 正文 链表: 正文 树与图: 树: leetcode236. 二叉树的最近公共祖先 递归(先序) leetcode124二叉树最大路径和 递归 图: leetcode 547朋 ...
- 牛客网在线编程_有序矩阵中第K小的元素
Leetcode378原题,所以一样没有数据范围...( log(max-min)二分答案,然后NlogN二分每一行求出小于答案的元素个数,为了保证二分的答案在矩阵中,二分写的要和平常不太一样,最后输 ...
随机推荐
- 【scala】apply和update
我们在使用scala的时候经常会用到对象的apply方法和update方法. 虽然我们表面没有察觉,但是实际上两个方法都会遵循相关约定被调用. apply apply方法的约定:用括号传递给变量(对象 ...
- requestAnimationFrame 与 cancelAnimationFrame
API接口 Window对象定义了以下两个接口: partial interface Window { long requestAnimationFrame(FrameRequestCallback ...
- Linux下安装SVN(Subversion)
一.安装直接运行命令用YUM安装: yum install subversion -y 二.创建版本库创建版本库用svnadmin create命令,大概语法是svnadmin create svn库 ...
- (三)java程序的编译和执行
编写java程序 eg class Demo { /* * 程序运行的入口 */ public static void main(String[] args) { System.out.println ...
- (效果二)js实现两个变量值的交换
ES5: var a = 12,b=13,c; c = a; a = b; b = c; console.log(a,b);//13,12 通过设置第三方变量交换赋值来实现 ES6 var a = ...
- 转载的,讲解java.util的集合类
本文是转载的 http://www.ibm.com/developerworks/cn/java/j-lo-set-operation/index.html#ibm-pcon 在实际的项目开发中会有很 ...
- 用eclipse来制作并使用可执行的jar文件
我近来用java写了一个股票收益分析的小程序,用于计算我的股票操作所带来的的收益.这里,记录了如何将源代码打包成可执行的命令的一个过程. 1:生成可执行的jar文件 选中工程,选择菜单中的export ...
- Python Requests快速入门
迫不及待了吗?本页内容为如何入门Requests提供了很好的指引.其假设你已经安装了Requests.如果还没有, 去 安装 一节看看吧. 首先,确认一下: Requests 已安装 Requests ...
- python的正则re模块
一. python的正则 python的正则模块re,是其内置模块,可以直接导入,即import re.python的正则和其他应用的正则及其相似,有其他基础的话,学起来还是比较简单的. 二. 正则前 ...
- 转载 fpga中 restoring 和 non-restoring 除法实现。
对于non-restoring方法,主要是用rem和den移位数据比较,rem_d长度为den+nom的总长,den_d长度为den+nom的总长度,rem_d的初始值为{{d_width{1'b0} ...