Search In Sorted Matrix I

Given a 2D matrix that contains integers only, which each row is sorted in an ascending order. The first element of next row is larger than (or equal to) the last element of previous row.

Given a target number, returning the position that the target locates within the matrix. If the target number does not exist in the matrix, return {-1, -1}.

Assumptions:

  • The given matrix is not null, and has size of N * M, where N >= 0 and M >= 0.

Examples:

matrix = { {1, 2, 3}, {4, 5, 7}, {8, 9, 10} }

target = 7, return {1, 2}

target = 6, return {-1, -1} to represent the target number does not exist in the matrix.

 
 1 public int[] search(int[][] matrix, int target) {
 2     // Write your solution here
 3     if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
 4         return new int[] {-1,-1} ; 
 5     }
 6     
 7     int n = matrix.length, m = matrix[0].length ; 
 8     int left = 0 , right = n*m-1 ; 
 9     int[] res = {-1,-1} ; 
10     /*
11         rowIndex: index/m 
12       colIndex: index%m 
13     */
14     //this is classical binary search: <= +1 -1 
15     while(left <= right){
16         int mid = left + (right - left )/2 ; 
17       int rowIndex = mid/m ; // /0 corner case already considered
18       int colIndex = mid%m ; 
19       if(matrix[rowIndex][colIndex] == target){
20           res[0] = rowIndex ; 
21         res[1] = colIndex ; 
22         return res ; 
23       } else if(matrix[rowIndex][colIndex] < target){
24           left = mid + 1 ; 
25       } else {
26           right = mid - 1 ; 
27       }
28     }
29     return res ; 
30   }
原文地址:https://www.cnblogs.com/davidnyc/p/8468524.html