• 240.Search a 2D Matrix II


    题目链接:https://leetcode.com/problems/search-a-2d-matrix-ii/description/

    题目大意:一个矩阵,每行从左到右,数值以升序排列;每列从上到下,数值以升序排列。从这个矩阵中找到是否有target数值存在,如果有返回true,否则返回false。

    解法一:利用74题的解法一,逐一的对每一行进行二分查找操作。代码如下(耗时15ms):

     1     public boolean searchMatrix(int[][] matrix, int target) {
     2         if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
     3             return false;
     4         }
     5         //逐一查找每一行
     6         for(int i = 0; i < matrix.length; i++) {
     7             //二分查找
     8             int low = 0, high = matrix[i].length - 1;
     9             while(low <= high) {
    10                 int mid = (low + high) / 2;
    11                 if(matrix[i][mid] < target) {
    12                     low = mid + 1;
    13                 }
    14                 else if(matrix[i][mid]> target) {
    15                     high = mid - 1;
    16                 }
    17                 else {
    18                     return true;
    19                 }
    20             }
    21         }
    22         return false;
    23     }
    View Code

    解法二:巧妙的解法,因为每行每列的数值按照一定顺序排列,当当前值比target小时,则在当前行右移;当当前值比target大时,则在当前列上移,直到找到target或下标越界。代码如下(耗时15ms):

     1     public boolean searchMatrix(int[][] matrix, int target) {
     2         if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
     3             return false;
     4         }
     5         int row = matrix.length - 1, col = 0;
     6         while(row >= 0 && col < matrix[0].length) {
     7             if(matrix[row][col] < target) {
     8                 col++;
     9             }
    10             else if(matrix[row][col] > target) {
    11                 row--;
    12             }
    13             else {
    14                 return true;
    15             }
    16         }
    17         return false;
    18     }
    View Code
  • 相关阅读:
    凤凰网CEO刘爽称鄙视微博连说20个屁示不齿
    科技创业网站
    梦想,在路上
    小本创业
    rails relevent
    MBA = married but available
    把UTF8编码转换为GB2312编码[转]
    FSFS和VDFS存储方式的区别
    如何让phpmyadmin输入密码再进入
    dede后台登陆后一片空白的解决办法汇总
  • 原文地址:https://www.cnblogs.com/cing/p/8214731.html
Copyright © 2020-2023  润新知