【Leetcode】Search a 2D Matrix
来源:互联网 发布:淘宝清洗后钱该怎么办 编辑:程序博客网 时间:2024/06/11 12:18
题目链接:https://leetcode.com/problems/search-a-2d-matrix/
题目:
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
.
思路:
先搜索target在哪一行,再在这行上搜索target在哪一列,又因为两次搜索在行列上都是有序的,可以利用二分查找加快搜索速度。
算法时间复杂度为O(logn)。
算法:
public boolean searchMatrix(int[][] matrix, int target) {int left = 0, right = matrix.length, mid = 0, t = -1;while (left < right) { //找到target在哪一行if (right - left == 1) {//t = left;break;}mid = left + (right - left) / 2;if (target < matrix[mid][0]) {right = mid;} else if (target > matrix[mid][0]) {left = mid;} else {return true;}}left = 0;right = matrix[0].length - 1;while (left <= right) { //搜索在那一列mid = left + (right - left) / 2;if (target < matrix[t][mid]) {right = mid - 1;} else if (target > matrix[t][mid]) {left = mid + 1;} else {return true;}}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
- 徒步一千里 (1930) (長津惠山)
- golang---利用反射机制对结构体进行循环赋值
- POJ 2243 Knight Moves
- Sqoop_1. 基本架构及数据操作 -- 待完善
- POJ 3620 Avoid The Lakes
- 【Leetcode】Search a 2D Matrix
- 一些笔记
- 果然还是不够努力是吗?
- 【心灵感悟】—看【人生就是一次列车的旅行】PPT之感
- 八、深拷贝和浅拷贝
- 体力耗费
- VS设置中的MT(d)与MD(d)
- 图结构练习——最短路径
- php 入门基础 一