leetcode74. 搜索二维矩阵 ,你见过吗
生活随笔
收集整理的這篇文章主要介紹了
leetcode74. 搜索二维矩阵 ,你见过吗
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
編寫一個高效的算法來判斷?m x n?矩陣中,是否存在一個目標值。該矩陣具有如下特性:
每行中的整數(shù)從左到右按升序排列。
每行的第一個整數(shù)大于前一行的最后一個整數(shù)。
示例?1:
輸入:
matrix = [
? [1, ? 3, ?5, ?7],
? [10, 11, 16, 20],
? [23, 30, 34, 50]
]
target = 3
輸出: true
示例?2:
輸入:
matrix = [
? [1, ? 3, ?5, ?7],
? [10, 11, 16, 20],
? [23, 30, 34, 50]
]
target = 13
輸出: false
思路:整個二維數(shù)組是有序的,二分查找即可。
class Solution {public boolean searchMatrix(int[][] matrix, int target) {if (matrix == null || matrix.length == 0) {return false;}int row = matrix.length;int col = matrix[0].length;int start = 0;int end = row * col - 1;while (start <= end) {int mid = start + (end - start) / 2;if (matrix[mid / col][mid % col] == target)return true;else if (matrix[mid / col][mid % col] > target)end = mid - 1;else start = mid + 1;}return false;} }?
總結(jié)
以上是生活随笔為你收集整理的leetcode74. 搜索二维矩阵 ,你见过吗的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode105 前序中序遍历序列
- 下一篇: leetcode226 反转二叉树