[LeetCode] 74. Search a 2D Matrix 解题思路

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:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.

问题:在给定的已排序的二维矩阵中,判断是否包含某个整数。

思路:看到二维数组,首先想到的是二维数组和 一维数组可以直接转换,arr[i][j] 等于 arr[i*col + j]。而在一个已排序的一维数组中搜索一个元素,可以采用分治(Divide and Conquer)思想,更具体些就是二分搜索(Binary Search) 算法。

将上面的结合起来就是,先实现一维数组的二分搜索算法,然后将算法中的一位转换为二维数组即可。

 1 bool searchMatrix(vector<vector<int>>& matrix, int target) {
 2 
 3     if (matrix.size() == 0) {
 4         return false;
 5     }
 6     
 7     int col = (int)matrix[0].size();
 8     int row = (int)matrix.size();
 9     
10     if (col == 1 && row == 1) {
11         return ( matrix[0][0] == target );
12     }
13     
14     int lm = 0;
15     int rm = col * row - 1;
16     
17     while (lm < rm ) {
18         
19         
20         if (lm + 1 == rm) {
21             int quoL = lm / col;
22             int remL = lm % col;
23             
24             int quoR = rm / col;
25             int remR = rm % col;
26             
27             if (matrix[quoL][remL] == target || matrix[quoR][remR] == target) {
28                 return true;
29             }else{
30                 return false;
31             }
32         }
33         
34         int midm = (lm + rm) / 2;
35         
36         int quo = midm / col;
37         int rem = midm % col;
38         
39         if (matrix[quo][rem] == target) {
40             return true;
41         }
42         
43         if (matrix[quo][rem] < target) {
44             lm = midm;
45         }else{
46             rm = midm;
47         }
48     }
49     
50     return false;
51 }

 

posted @ 2015-12-26 09:34  TonyYPZhang  阅读(537)  评论(0编辑  收藏  举报