剑指offer第三题:二维数组中查找

来源:互联网 发布:kindle看编程书籍 编辑:程序博客网 时间:2024/06/05 09:23
package java_study.JianZhiOffer;import java_study.sort.Sort7;import org.junit.Test;import java.util.Arrays;import java.util.Random;/** * Created by ethan on 2015/6/20. * 在二维数组种找一个数 * 剑指offer第三题:二维数组种查找 */public class NO3FindIn2DimensionArray {    public int[][] arr = {{2,5,9,19,21},{3, 6,11, 21, 25},{5, 8, 18, 28, 32},{8, 11, 31, 39, 49}};    public boolean find(int[][] arr, int goal){        if (arr == null) return false;        int row = 0;        int col = arr[0].length-1;        while(row<arr.length && col>=0){            if (arr[row][col] == goal) return true;            if (arr[row][col] > goal) col--;            else row++;        }        return false;    }//    public int[][] init(int row, int col){//        int[][] arr = new int[row][col];//        Random random = new Random();//        for (int i=0; i<row; i++){//            for (int j=0; j<col; j++){//                arr[i][j] = random.nextInt(100);//            }//            Arrays.sort(arr[i]);//        }//        return arr;//    }    public void print_array(int[][] arr){        for (int i=0; i<arr.length; i++){            for (int j=0; j<arr[i].length; j++){                System.out.print(arr[i][j] + " ");            }            System.out.println();        }    }    @Test    public void test(){        System.out.println("find it");        print_array(arr);        System.out.println(find(arr, 25));    }}

0 0
原创粉丝点击