首页 > 其他 > 详细

<剑指offer> 第1题

时间:2019-06-10 22:48:10      阅读:94      评论:0      收藏:0      [点我收藏+]

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

 

基础做法:

逐个遍历数组元素,直到找到元素为止

public class Solution {
      public boolean Find(int target, int [][] array) {
        for(int i = 0; i < array.length; i ++){
            for(int n = 0; n < array[i].length; n++){
                if(array[i][n] == target) 
                    return true;
            }
        }
        return false;
    }
}

 

 

进阶做法:

首先选取数组中右上角的数字。如果该数字是要查找的数字,查找过程结束。

如果该数字大于要查找的数字,剔除数字所在列;如果该数字小于要查找的数字,剔除这个数字所在的行,一步步缩小查找的范围,直到找到要查找的数字,或者查找范围为空。

public class Solution {
     public boolean Find(int target, int [][] array) {
        int row = 0; //起始的行数
        int col = array[0].length - 1; //起始的列数
        
        while((row < array.length) && (col >= 0)){
            if(target == array[row][col]){ //如果找到了直接退出,返回true
                return true;
            }else if(target < array[row][col]){ //如果找到的数比target大,那么target应该在左边
                col --;
            }else{//如果找到的数比target小,那么target应该在数的下边
                row ++; 
            }
        }
        return false;
    }
}

 

<剑指offer> 第1题

原文:https://www.cnblogs.com/HarSong13/p/11000544.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!