[leetcode] Search a 2D matrix
来源:互联网 发布:时间同步软件apk 编辑:程序博客网 时间:2024/06/16 11:57
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
.
思路:很容易发现所有数已经排过序,则可以用二分查找,注意将index转化成二维坐标。
public class Solution { public int[] findpos(int num, int row, int col){ int[] pos = new int[2]; pos[0] = num / col; pos[1] = num % col; return pos; } public boolean searchMatrix(int[][] matrix, int target) { int row = matrix.length; int col = matrix[0].length; int total = row*col; int hi = total - 1; int low = 0; while(low <= hi){ int mid = (low + hi)/2; int[] pos = findpos(mid, row, col); int number = matrix[pos[0]][pos[1]]; if(number == target) return true; else if(number < target) low = mid + 1; else hi = mid - 1; } return false; }}
0 0
- [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
- LeetCode - Search a 2D Matrix
- LeetCode:Search a 2D Matrix
- LeetCode 74: Search A 2D Matrix
- leetcode之Search a 2D Matrix
- 蓝桥杯-入门训练-BEGIN-1-4题
- 中华精英会:IT应用技术的催化剂
- 蓝桥杯-基础练习-BASIC-1-5
- 十年磨一剑!
- Request —— 让 Node.js http请求变得超简单
- [leetcode] Search a 2D matrix
- 蓝桥杯-基础练习-BASIC-6-杨辉三角形
- 蓝桥杯-基础练习-BASIC-7-特殊的数字
- 蓝桥杯-基础练习-BASIC-8-回文数
- 蓝桥杯-基础练习-BASIC-9-特殊回文数
- 蓝桥杯-基础练习-BASIC-10-十进制转十六进制
- 蓝桥杯-基础练习-BASIC-11-十六进制转十进制
- 蓝桥杯-基础练习-BASIC-12-十六进制转八进制
- 蓝桥杯-基础练习-BASIC-13-数列排序