Leetcode刷题记—— Search a 2D Matrix(在二维数组里查找)
来源:互联网 发布:淘宝 iphone att群 编辑:程序博客网 时间:2024/05/16 17: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
.
Subscribe to see which companies asked this question
二、解题思路:
本题很简单,使用二分查找即可,只是比较时需要将mid值转换为数组横纵坐标即可,通过将mid/列数得到横坐标,mid%列数得到纵坐标即可。
三、源码:
public class Solution{ public boolean searchMatrix(int[][] matrix, int target) { int x = matrix.length; if (x == 0) return false; int y = matrix[0].length; //int length = x * y; int lo = 0; int hi = x * y - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (matrix[mid / y][mid % y] < target) lo = mid + 1; else if (matrix[mid / y][mid % y] > target) hi = mid - 1; else return true; } return false; } public static void main(String args[]) { int[][] matrix = {}; Solution solution = new Solution(); System.out.println(solution.searchMatrix(matrix, 9)); }}
0 0
- Leetcode刷题记—— Search a 2D Matrix(在二维数组里查找)
- [算法][LeetCode]Search a 2D Matrix——二维数组的二分查找
- leetcode——Search a 2D Matrix 二维有序数组查找(AC)
- Search a 2D Matrix(在二维数组中查找)
- (二维数组中查找target)LeetCode#74. Search a 2D Matrix #240. Search a 2D Matrix II
- [LeetCode]—Search a 2D Matrix 有序二维矩阵中查找目标值
- 字符串算法——二维有序数组中查找目标值(Search a 2D Matrix)
- 字符串算法——查找二维数组中元素(Search a 2D Matrix II)
- 【LeetCode】Search a 2D Matrix && 【九度】题目1384:二维数组中的查找
- Leetcode 74 Search a 2D Matrix 有序二维数组二叉查找
- Search a 2D Matrix 在有序二维矩阵查找数 @LeetCode
- leetcode解题之 Search a 2D Matrix java 版(在二维矩阵中查找)
- Leetcode刷题记—— 33. Search in Rotated Sorted Array(在翻转顺序的数组里查找)
- LeetCode 查找 Search a 2D Matrix
- Leetcode 240 Search a 2D Matrix II (二分法和分治法解决有序二维数组查找)
- 剑指offer 面试题3:二维数组(矩阵)中数的查找(leetcode 74. Search a 2D Matrix) 题解
- LeetCode | Search a 2D Matrix(二维矩阵中查找)
- LeetCode OJ 之 Search a 2D Matrix II (二维矩阵查找)
- 简单几步实现网络音乐播放器(Qt版百度FM)
- MongoDB的使用及集群搭建
- 数据结构——链队列——2016_12_27
- bzoj 2400: Spoj 839 Optimal Marks
- TCP与应用层协议
- Leetcode刷题记—— Search a 2D Matrix(在二维数组里查找)
- Linux内核模块
- 第3章-1 创建ndarray 学习笔记
- 2016这一年读过的那些书
- 【oracle游标二】游标循环方式
- Waiting for table metadata lock
- 性能优化一点总结
- 按钮点击展开菜单列表
- Hadoop运维(2) Hive部署