码迷,mamicode.com
首页 > 其他好文 > 详细

Search In Sorted Matrix I

时间:2018-02-25 11:12:44      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:next   sum   class   ssi   contain   nbsp   matrix   gpo   res   

 

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   }

 

Search In Sorted Matrix I

标签:next   sum   class   ssi   contain   nbsp   matrix   gpo   res   

原文地址:https://www.cnblogs.com/davidnyc/p/8468524.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!