zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    Python 学习笔记 11.模块(Module)
    Python 学习笔记 8.引用(Reference)
    Python 学习笔记 9.函数(Function)
    Python 学习笔记 6.List和Tuple
    Python 学习笔记 4.if 表达式
    Python 学习笔记 2.自省
    Python 学习笔记 3.简单类型
    Python 学习笔记 7.Dictionary
    Python 学习笔记 5.对象驻留
    Python 学习笔记 10.类(Class)
  • 原文地址:https://www.cnblogs.com/lailailai/p/3657325.html
Copyright © 2011-2022 走看看