zoukankan      html  css  js  c++  java
  • 二维数组中的查找

    在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数

    思路1:在每一行使用二分查找

     1 public class Solution {
     2     public boolean Find(int target, int [][] array) {
     3          for(int i=0;i<array.length;i++){
     4              int low=0;
     5              int high=array[i].length-1;
     6               while(low<=high){
     7                  int mid=(low+high)/2;
     8                  if(target>array[i][mid])
     9                      low=mid+1;
    10                  else if(target<array[i][mid])
    11                      high=mid-1;
    12                  else
    13                      return true;
    14              }
    15          }
    16          return false;
    17     }
    18 }

    思路二:从右下角开始,如果比他小就i递减,如果比他大就j递加,或者从右 上角开始,如果比他小就j递减,如果比他大就i递加

    public class Solution {
        public boolean Find(int target, int [][] array) {
      int row=0;
            int col=array[0].length-1;
            while(row<=array.length-1&&col>=0){
                if(target==array[row][col])
                    return true;
                else if(target>array[row][col])
                    row++;
                else
                    col--;
            }
            return false;
     
        }
    }
  • 相关阅读:
    SpringRequestContext源码阅读
    MyBatis事务管理源码阅读
    linux查找依赖文件
    GitHub
    Qt Quick
    centos7下安装chrome
    软件使用
    排序算法之冒泡排序
    c++学习
    cent6.4使用
  • 原文地址:https://www.cnblogs.com/wxw7blog/p/7226071.html
Copyright © 2011-2022 走看看