zoukankan      html  css  js  c++  java
  • 矩阵中找数

            给定一个有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(N+M),额外空间复杂度为O(1)。
    方法:因为排序好的,所以从第一行右侧开始查找
    public class PrintFindNumberSortMatrix {
    public static boolean printFindNumberSortMatrix(int Matrix[][],int K){
    int curR = 0; //默认行为0
    int curC = Matrix[0].length-1; //默认列为最后一列
    while (curR<=Matrix.length-1&&curC>=0){ //临界判断条件
    if (Matrix[curR][curC]==K){
    return true;
    }else if(Matrix[curR][curC]>K){ //找的数比矩阵数大则列减一
    curC--;
    }else if(Matrix[curR][curC]<K){//找的数比矩阵数小则行加一
    curR++;
    }
    }
    return false;
    }

    public static void main(String[] args) {
    int Matrix[][] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
    System.out.print(printFindNumberSortMatrix(Matrix,100));
    }
    }
    总结:根据题意,从第一行右侧开始判断,之后就很容易了。
  • 相关阅读:
    【对拍√】
    hdu5791 TWO
    luogu P1220 关路灯
    【NOI2001】食物链
    【HAOI2016】食物链
    luogu P1006 传纸条
    可持久化平衡树
    可持久化并查集
    线段树合并(【POI2011】ROT-Tree Rotations)
    可持久化数组
  • 原文地址:https://www.cnblogs.com/liuwentao/p/9439887.html
Copyright © 2011-2022 走看看