赞
踩
class Solution { public boolean searchMatrix(int[][] matrix, int target) { // 使用二分查找 // 将矩阵写入一个数组中 然后使用二分查找算法 int[] a = new int[matrix.length * matrix[0].length]; int k = 0; // 将所有元素写入a for(int i = 0; i < matrix.length; i++){ for(int j = 0; j < matrix[0].length; j++){ a[k++] = matrix[i][j]; } } int low = 0; int high = a.length - 1; while(low <= high){ int mid = (high - low) / 2 + low; if(a[mid] == target){ return true; }else if(a[mid] > target){ high = mid - 1; }else if(a[mid] < target){ low = mid + 1; } } return false; } }
class Solution { public boolean searchMatrix(int[][] matrix, int target) { // 将二维矩阵的索引转换为一维数组的索引 // 假设矩阵是m行n列 // 那么(i,j)的绝对索引 idx = i * n + j // 那么知道idx 就可以知道 i = idx / n j = idx % n int m = matrix.length; int n = matrix[0].length; int left = 0; int right = m * n - 1; while(left <= right){ int mid = left + (right - left + 1) / 2; int i = mid / n; int j = mid % n; if(matrix[i][j] == target){ return true; }else if(matrix[i][j] < target){ left = mid + 1; }else{ right = mid - 1; } } return false; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。