LeetCode Search a 2D Matrix

 1 class Solution {
 2 public:
 3     bool searchMatrix(vector<vector<int> > &matrix, int target) {
 4         int rows, cols;
 5         if (!(rows = matrix.size()) || !(cols = matrix[0].size())) return false;
 6         int ridx, cur, first = -1, last = rows;
 7         while (first + 1 < last) {
 8             ridx = (first + last) / 2;
 9             cur = matrix[ridx][0];
10             if (cur < target) {
11                 first = ridx;
12             } else if (cur > target) {
13                 last = ridx;
14             } else {
15                 break;
16             }
17         }
18         if (first + 1 == last) {
19             ridx = first;
20         } else {
21             return true;
22         }
23         if (ridx < 0 || ridx >= rows) return false;
24         return binary_search(matrix[ridx].begin(), matrix[ridx].end(), target);
25     }
26 };

先用二分找到合适范围的行索引,然后在该行上搜索,在整个范围上搜索的话也可以貌似复杂度更低一点,代码如下

 1 class Solution {
 2 public:
 3     bool searchMatrix(vector<vector<int> > &matrix, int target) {
 4         int rows, cols;
 5         if (!(rows = matrix.size()) || !(cols = matrix[0].size())) return false;
 6         int first = 0, last = rows * cols - 1;
 7         while (first <= last) {
 8             int mi = (first + last) / 2;
 9             int mv = matrix[mi / cols][mi % cols];
10             if (mv > target) {
11                 last = mi - 1;
12             } else if (mv < target) {
13                 first= mi + 1;
14             } else {
15                 return true;
16             }
17         }
18         return false;
19     }
20 };

 

二分搜索android sdk里有个代码感觉很不错

 1 // 未找到,返回应该插入的索引位置的负值
 2 private static int binarySearch(int[] a, int start, int len, int key) {
 3     int high = start + len, low = start - 1, guess;
 4 
 5     while (high - low > 1) {
 6         guess = (high + low) / 2;
 7 
 8         if (a[guess] < key)
 9             low = guess;
10         else
11             high = guess;
12     }
13 
14     if (high == start + len)
15         return ~(start + len);
16     else if (a[high] == key)
17         return high;
18     else
19         return ~high;
20 }

 

posted @ 2014-04-10 20:30  卖程序的小歪  阅读(187)  评论(0编辑  收藏  举报