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 }

 

转载于:https://www.cnblogs.com/lailailai/p/3657325.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值