• LeetCode: Search a 2D Matrix


    少数次过

     1 class Solution {
     2 public:
     3     bool searchMatrix(vector<vector<int> > &matrix, int target) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         int m = matrix.size();
     7         int n = matrix[0].size();
     8         int left = 0;
     9         int right = m-1;
    10         int mid;
    11         while (left <= right) {
    12             mid = (left+right)/2;
    13             if (target == matrix[mid][0]) return true;
    14             if (target > matrix[mid][0]) left = mid+1;
    15             else right = mid-1;
    16         }
    17         int row = (left+right)/2;
    18         left = 0;
    19         right = n-1;
    20         while (left <= right) {
    21             mid = (left+right)/2;
    22             if (target == matrix[row][mid]) return true;
    23             if (target > matrix[row][mid]) left = mid+1;
    24             else right = mid-1;
    25         }
    26         return false;
    27     }
    28 };

     C#

     1 public class Solution {
     2     public bool SearchMatrix(int[,] matrix, int target) {
     3         int m = matrix.GetLength(0);
     4         int n = matrix.GetLength(1);
     5         int left = 0;
     6         int right = m - 1;
     7         int mid = 0;
     8         while (left <= right) {
     9             mid = (left + right) / 2;
    10             if (target == matrix[mid, 0]) return true;
    11             if (target > matrix[mid, 0]) left = mid + 1;
    12             else right = mid - 1;
    13         }
    14         int row = (left + right) / 2;
    15         left = 0;
    16         right = n - 1;
    17         while (left <= right) {
    18             mid = (left + right) / 2;
    19             if (target == matrix[row, mid]) return true;
    20             if (target > matrix[row, mid]) left = mid + 1;
    21             else right = mid - 1;
    22         }
    23         return false;
    24     }
    25 }
    View Code
  • 相关阅读:
    计算机三级数据库-指导
    spring导入约束
    hibernater获取session时org.hibernate.service.spi.ServiceException错误
    springxml配置注入报错
    右键复制类的完整路径
    关于实体里的toString方法
    idea创建web项目环境
    框架快速找类
    如何在scdn博客里搜索自己博客文章
    永久消除自动产生的QQPCMgr
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3032774.html
Copyright © 2020-2023  润新知