1. 程式人生 > >Leetcode 搜尋二維矩陣 II

Leetcode 搜尋二維矩陣 II

編寫一個高效的演算法來搜尋 m x n 矩陣 matrix 中的一個目標值 target。該矩陣具有以下特性:

  • 每行的元素從左到右升序排列。
  • 每列的元素從上到下升序排列。

示例:

現有矩陣 matrix 如下:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

給定 target = 5,返回 true

給定 target = 20,返回 false

 

思路:先二分target在哪一行,然後在對行進行二分找在哪一列

 1 boolean searchMatrix(int[][] matrix, int target) {
 2         if(matrix.length==0||matrix[0].length==0)
 3         {
 4             return false;
 5         }
 6         
 7         int l=0,r=matrix.length-1;
8 int mid=0; 9 while(l<=r) 10 { 11 mid=(l+r)/2; 12 if(target==matrix[mid][0]) 13 return true; 14 else if(target>matrix[mid][0]) 15 l=mid+1; 16 else r=mid-1; 17 } 18 for
(int i=0;i<=mid;i++) 19 { 20 int left=0,right=matrix[0].length-1; 21 while(left<=right) 22 { 23 int m=(left+right)/2; 24 if(matrix[i][m]==target) 25 return true; 26 else if(matrix[i][m]<target) 27 left=m+1; 28 else right=m-1; 29 } 30 } 31 return false; 32 33 }
View Code