jzoffer-st-1:二维数组中查找

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011877584/article/details/81879087

package com.fjf.test;

/**
* 二维数组中查找
*
* 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,
* 每一列都按照从上到下递增的顺序排序。
* 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
* @author fjf
*
*/
public class Test01 {

public static void main(String[] args) {
    int[][] data = new int[][]{{1,2,3},{4,5,6},{7,8,9}};
    int target = 5; 
    Solution s = new Solution();

    if(s.Find1(target, data)){
        System.out.println("找到了!");
    }else{
        System.out.println("无此数据!");
    }


}

}

class Solution {

//蛮力法 O(n*n)
public boolean Find(int target, int [][] array) {
    boolean isHave = false;
    outer:for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
            if(target==array[i][j]){
                isHave = true; 
                break outer;
            }
        }
    }
      return isHave;
}

//从左下角  或者 右上角开始 。这里我们用左下角   O(n)
public boolean Find1(int target, int [][] array) {
    int rowcount = array.length;
    int colcount = array[0].length;
    //左下角的数array[rowcount-1][0]
    int i = rowcount -1;
    int j = 0;
    while(i>=0&&j<colcount){
        if(target>array[i][j]){
            j++;
        }else if(target<array[i][j]){
            i--;
        }else {
            return true;
        }
    }
    return false;
}

}

猜你喜欢

转载自blog.csdn.net/u011877584/article/details/81879087
今日推荐