赞
踩
给你一个满足下述两条属性的 m x n 整数矩阵:
给你一个整数 target ,如果 target 在矩阵中,返回 true ;否则,返回 false 。
示例 1:
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
输出:true
public class SearchMatrix { public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return false; } int rows = matrix.length; int cols = matrix[0].length; int row = 0; int col = cols - 1; while (row < rows && col >= 0) { if (matrix[row][col] == target) { return true; } else if (matrix[row][col] > target) { col--; } else { row++; } } return false; } public static void main(String[] args) { SearchMatrix solution = new SearchMatrix(); int[][] matrix = {{1,3,5,7},{10,11,16,20},{23,30,34,60}}; int target = 34; System.out.println("Target exists: " + solution.searchMatrix(matrix, target)); // Output: true } }
时间复杂度:O(m + n),其中m为矩阵的行数,n为矩阵的列数。因为每次迭代都会将行索引或列索引移动一次,最多移动m + n次。
空间复杂度:O(1)。
public class SearchMatrix { public boolean searchMatrix(int[][] matrix, int target) { int m = matrix.length; int n = matrix[0].length; 二分查找第一列,找到最后一个小于等于 target 的元素所在的行 int left = 0; int right = m - 1; while (left <= right) { int mid = (left + right ) / 2; if (matrix[mid][0] == target) { return true; } else if (matrix[mid][0] < target) { left = mid + 1; } else { right = mid - 1; } } // 如果目标值不在矩阵的第一列,则在确定的行中继续进行二分查找 if (right >= 0) { //确定搜索行数 int row = right; left = 0; right = n - 1; while (left <= right) { int mid = (left + right ) / 2; if (matrix[row][mid] == target) { return true; } else if (matrix[row][mid] < target) { left = mid + 1; } else { right = mid - 1; } } } return false; } public static void main(String[] args) { SearchMatrix solution = new SearchMatrix(); int[][] matrix = {{1,3,5,7},{10,11,16,20},{23,30,34,60}}; int target = 34; System.out.println("Target exists: " + solution.searchMatrix(matrix, target)); // Output: true } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。