【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