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: Given target = 3, return true.算法
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
給定一個二維矩陣,實現一個算法在矩陣中實現快速搜索。即給定k,在矩陣中搜索k
矩陣中下面的性質:每一行每一列都是排好序的,每一行的第一個數都比上一行的最後一個數大。數組
解法一:先用二叉查看找算法找到數字所在的列,再用二叉查找算法找數字所在的列。找到就返回true,不然返回false。ide
算法實現類spa
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return false; } int row = matrix.length; int column = matrix[0].length; int low = 0; int high = row - 1; int mid = 0; // 找結果所在的列 while (low <= high) { mid = low + (high - low) / 2; if (target < matrix[mid][column - 1]) { high = mid - 1; } else if (target > matrix[mid][column - 1]) { low = mid + 1; } else { return true; } } // 決定列所在的最終位置 int targetRow = mid; if (matrix[mid][column - 1] < target) { targetRow++; } // 目標列超出,無結果 if (targetRow >= row) { return false; } low = 0; high = column - 1; // 找所在的行,找到返回true,沒有返回false while (low <= high) { mid = low + (high - low) / 2; if (target < matrix[targetRow][mid]) { high = mid - 1; } else if (target > matrix[targetRow][mid]) { low = mid + 1; } else { return true; } } return false; } }
解法二:
.net
解題思路:
首先,咱們選擇查找數子7爲例來一步步分析查找的過程。
而後,咱們選取數組右上角的9。
code
代碼實現:ci
package array; public class QuencyArray { public static boolean FindArray(int[][] arr,int number){ int rows = arr.length; int columns = arr[0].length; boolean flag = false; if(arr!=null && rows>0 && columns>0){ int row = 0; int col = columns-1; while(row0){ if(arr[row][col]number){//說明待查找的數在左方 col--; }else { flag = true; break; } } } return flag; } public static void main(String[] args) { int[][] arr = { {1,2,8,9}, {2,4,9,12}, {4,7,10,13}, {6,8,11,15}, {8,10,14,17} }; System.out.println(FindArray(arr,8));//true System.out.println(FindArray(arr,22));//false } }
第一次查找咱們選取的是數組右上角進行查詢,一樣咱們能夠選取數組的左下角。 或者:get