剑指offer-二维数组中的查找

题目描述:

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

分析:

  • 首先选取数组的右上角数字,若等于查找数字,返回true;
  • 如果该数字大于查找的数字,剔除这个数所在的列;
  • 如果该数字小于查找的数字,剔除这个数所在的行。这样每一步都会缩小查找范围。
public class Solution {
    public boolean Find(int [][] array,int target) {
        if(array.length <= 0 ) return false;
        int rows = array.length;
        int columns = array[0].length;
          int i = 0;
        int j = columns - 1;
        while(i>=0 && i<rows && j>=0 && j <columns) {
            if(target > array[i][j]) {
                i ++;
            } else if(target < array[i][j]) {
                j --;
            } else {
                return true;
            }       
        }
        return false;
    }
}

 

posted @ 2016-08-10 14:05  no_one  阅读(251)  评论(0编辑  收藏  举报