LeetCode 074 Search a 2D Matrix
来源:互联网 发布:insert pl sql 编辑:程序博客网 时间:2024/05/22 15:11
题目说明
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
Given target = 3, return true.
分析
把二维数组看成一维数组,用二分查找。
代码
public static boolean searchMatrix(int[][] matrix, int target) { int mx = matrix.length; int my = matrix[0].length; int l = 0; int r = mx * my; while (l < r) { int m = l + (r - l) / 2; // 将m转换成x、y int x = m / my; int y = m % my; // 二分查找:matrix[x][y]转换成一维数组,坐标就是m if (matrix[x][y] == target) { return true; } else if (matrix[x][y] < target) { l = m + 1; } else { r = m; } } return false; }
0 0
- LeetCode 074 Search a 2D Matrix
- LeetCode: Search a 2D Matrix [074]
- LeetCode 074 Search a 2D Matrix
- leetcode 074 Search a 2D Matrix
- [leetcode][Search] Search a 2D Matrix
- LeetCode: Search a 2D Matrix
- LeetCode Search a 2D Matrix
- [Leetcode] Search a 2D Matrix
- LeetCode : Search a 2D Matrix
- [LeetCode] Search a 2D Matrix
- Leetcode 74 Search a 2D Matrix
- leetcode 90: Search a 2D Matrix
- [LeetCode]Search a 2D Matrix
- [Leetcode] Search a 2-D matrix
- [Leetcode]Search a 2D Matrix
- [leetcode]Search a 2D Matrix
- LeetCode-Search a 2D Matrix
- [leetcode] Search a 2D Matrix
- objective-c 中随机数的用法 (3种:arc4random() 、random()、CCRANDOM_0_1() )
- linux读书笔记4
- 从0开始<五>:字符串相关-htoi函数,删除字符串中指定字符
- 其他高级算法
- sql统计查询——求不同类别的平均值
- LeetCode 074 Search a 2D Matrix
- 1000~ 5000之间有多少整数,其各位数字之和为5,分别是哪些数(例如整数2003的各位数字之和为 2+0+0+3 ,等于5))
- Java中的Random()函数
- 【PAT】1017. Queueing at Bank (25)
- C语言 gets()和scanf()函数的区别
- 缘起CSDN之『进进出出』——如何退出CSDN
- 面向对象
- 1034. 有理数四则运算(20)
- 使用DatePickerDialog和TimePickerDialog实现日期和时间选择对话框