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二分每一行求出小于答案的元素个数,为了保证二分的答案在矩阵中,二分写的要和平常不太一样,最后输 ...
随机推荐
- 22-THREE.JS 面材质
<!DOCTYPE html> <html> <head> <title>Example 04.05 - Mesh face material</ ...
- IIS(IISReset.exe)命令行
(转自:http://www.cnblogs.com/itech/archive/2009/05/18/1459231.html) 一 IIS命令行 Iisreset.exe 的概述 Iisreset ...
- 9.链表中倒数第k个结点[FindReverseKthLinkedListNode]
[题目] 输入一个单向链表,输出该链表中倒数第k个结点.链表的倒数第0个结点为链表的尾指针.链表结点定义如下: C++ Code 12345 struct ListNode { int ...
- tab显示不同数据
效果 核心代码 [js] [#escape x as (x)!?html]<!doctype html><html lang="zh-CN"><hea ...
- matlab中hdl coder 的使用
今天摸索了一下hdl coder的使用方法,各个步骤主要是照猫画虎,有些地方还是不理解,先总结一下: 1.要想调用quartus或者Xilinx综合布局布线需要先设置,设置的方法有两种,命令窗口输入 ...
- 转载Verilog乘法器
1. 串行乘法器 两个N位二进制数x.y的乘积用简单的方法计算就是利用移位操作来实现. module multi_CX(clk, x, y, result); input clk; input [7: ...
- 数据库中字段的数据类型与JAVA中数据类型的对应关系
类型名称 显示长度 数据库类型 JAVA类型 JDBC类型索引(int) 描述 VARCHAR L+N VARCHAR java.lang.String 12 CHAR N ...
- CoreDNS kubernetes 安装使用
kubernetes 以前是skydns 后面变为 dnsmasq,coredns 也是一个不错的工具 1. 准备环境 安装 kubernetes 配置 kubelet 的cluster-dns 2 ...
- The type org.springframework.context.ConfigurableApplicationContext cannot be resolved问题解决
在搭建maven项目的时候,有时候会报这样的问题. The type org.springframework.context.ConfigurableApplicationContext cannot ...
- 关于yii2 REST api 的问题
首先,需要在basic/web/文件夹下添加一个.htaccess文件 这样进入项目就会自动访问index.php文件,url就不会错乱了 <IfModule mod_rewrite.c> ...