• 数组和矩阵问题:在行列都排好序的矩阵中找数


    题目

      给定一个有 N*M 的整型矩阵 matrix 和一个整数 K,matrix 的每一行和每一列都是排好序的。实现一个函数,判断 K 是否在 matrix 中。

      例如:

      0  1  2  5

      2  3  4  7

      4  4  4  8

      5  7  7  9

      如果 K 为 7,返回 true; 如果 K 为 6,返回 false。

    要求

      时间复杂度为 O(M+N), 额外空间复杂度为 O(1)。

    难度

      一星

    解答

      注意到该矩阵行列都是排好序的,可以从右上角或者左下角开始与K进行比较。

      下面说明从右上角的数开始寻找的方法:

      1. 从矩阵右上角的数开始寻找(row=0, col=M-1),注意到 matrix[row][col] 左边的数都小于等于 matrix[row][col],下边的数都大于等于 matrix[row][col]。

      2. 比较当前数 matrix[row][col] 与 K 的关系:

    • 如果与 K 相等,说明已被找到,直接返回 true;
    • 如果大于 K,说明 K 有可能在 matrix[row][col] 的左边,令 col = col-1, 重复步骤2;
    • 如果小于 K,说明 K 有可能在 matrix[row][col] 的下边,令 row = row+1,重复步骤2;

      3. 如果找到越界都没有发现与 K 相等的数,则返回 false.

     1 public class Main {
     2     public static void main(String[] args) {
     3         int[][] matrix = {{0,1,2,5},{2,3,4,7},{4,4,4,8},{5,7,7,9}};
     4         System.out.println(new Main().isContains(matrix, 7)); //true
     5         System.out.println(new Main().isContains(matrix, 6)); //false
     6     }
     7     
     8     public boolean isContains(int[][] matrix, int K){
     9         //从右上角的数开始与 K 进行比较
    10         int row = 0;
    11         int col = matrix[0].length - 1;
    12         while(row < matrix.length && col > -1){
    13             if(matrix[row][col] == K){ //若找到与 K相等的数直接返回 true
    14                 return true;
    15             }else if(matrix[row][col] > K){ //若大于K, 则K有可能在 matrix[row][col] 的左边
    16                 col--;
    17             }else{ //若大于K, 则K有可能在 matrix[row][col] 的下边
    18                 row++;
    19             }
    20         }
    21         return false;
    22     }
    23 }

       从左下角的数(row=N-1, col=0)开始寻找的方法与上述类似,注意到 matrix[row][col] 上边的数都小于等于 matrix[row][col],右边的数都大于等于 matrix[row][col]。具体代码可自行实现。

      

  • 相关阅读:
    第一天课程总结与心得体会
    面对一切新的事物。
    libgdx学习记录3——动画Animation
    Eclipse编辑器设置
    libgdx学习记录2——文字显示BitmapFont
    libgdx自制简易Flappy Bird
    libgdx学习记录1——图片显示Texture
    libgdx自制简易版Don't Touch The White Tile
    eclipse 最最最常用快捷键
    libgdx退出对话框
  • 原文地址:https://www.cnblogs.com/zlxyt/p/10522238.html
Copyright © 2020-2023  润新知