zoukankan      html  css  js  c++  java
  • Leetcode-Search a 2D Matrix

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

    • Integers in each row are sorted from left to right.
    • The first integer of each row is greater than the last integer of the previous row.

    For example,

    Consider the following matrix:

    [
      [1,   3,  5,  7],
      [10, 11, 16, 20],
      [23, 30, 34, 50]
    ]
    

    Given target = 3, return true.

    Have you met this question in a real interview?
     
    Analysis:
    This is a double binary search problem. First, we use binary search to determine the row in which the target is; Second, we use binary search to search the determined row.
     
    Solution:
     
     1 public class Solution {
     2     public boolean searchMatrix(int[][] matrix, int target) {
     3         int xLen = matrix.length;
     4         if (xLen==0) return false;
     5         int yLen = matrix[0].length;
     6         if (yLen==0) return false;
     7 
     8         //Determine row.
     9         int x = 0;
    10         int y = xLen-1;
    11         int k = -1;
    12         int targetRow = -1;
    13         while (targetRow==-1){
    14             if (y<x) return false;
    15 
    16             k = x + (y-x)/2;
    17             if (target<matrix[k][0]){
    18                 y = k-1;
    19                 continue; 
    20             } else if (target>matrix[k][yLen-1]){
    21                 x = k+1;
    22                 continue;
    23             } else {
    24                 targetRow = k;
    25                 continue;
    26             }
    27         }
    28 
    29         //Search the target element in the targetRow
    30         x = 0;
    31         y = yLen-1;
    32         k = -1;
    33         boolean findTarget = false;
    34         while (!findTarget){
    35             if (y<x) {
    36                 findTarget = false;
    37                 break;
    38             }        
    39          
    40             k=x+(y-x)/2;
    41             if (target==matrix[targetRow][k]){
    42                 findTarget = true;
    43                 break;
    44             } else if (target<matrix[targetRow][k]){
    45                 y = k-1;
    46                 continue;
    47             } else {
    48                 x = k+1;
    49                 continue;
    50             }
    51         }
    52         return findTarget;
    53     }
    54 }
  • 相关阅读:
    从零开始学Go之函数(一):匿名函数与闭包
    从零开始学Go之容器(四):列表
    从零开始学Go之容器(三):映射
    从零开始学Go之容器(二):切片
    从零开始学Go之容器(一):数组
    从零开始学Go之基本(五):结构体
    从零开始学Go之基本(四):流程控制语句
    从零开始学Go之基本(三):类型转换与常量
    Java 单例设计模式
    Java 数组
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4102627.html
Copyright © 2011-2022 走看看