Determine whether the two-dimensional array contains an integer, where the two-dimensional array rows and columns are ordered

Problem description: In a two-dimensional array (each one-dimensional array has the same length), each row is sorted in increasing order from left to right, and each column is sorted in increasing order from top to bottom. Please complete a function, input such a two-dimensional array and an integer, and determine whether the array contains the integer.

package hgy.java.arithmetic;
public class FindNumFromDeArray {
	
	public static boolean find(int target, int [][] array) {
		int row = array.length;//行
		int column = array[0].length;//列
		//System.out.println(row+" "+column);
    	//从左下角到右上角查询
    	int i = row-1;
    	int j = 0;
    	System.out.println(i + " " + j);
    	while(i>=0&&j<column){
    		if(array[i][j]==target)
    			return true;
    		else if(array[i][j]>target)
    			i--;
    		else if(array[i][j]<target)
    			j++;
    		System.out.println(i + " " + j);
    	}
        return false;
    }
    
    public static void main(String[] args) {
		int [][]arr = {{1,2,3,5,6},{2,4,5,7,9},{4,5,6,8,9}};
		//System.out.println(Arrays.deepToString(arr));
		//打印二维数组
		for(int[]a:arr){
			for(int aa:a)
				System.out.print(aa+" ");
			System.out.println();
		}
		System.out.println(find(9,arr));	
	}
}
Published 6 original articles · Likes0 · Visits 18

Guess you like

Origin blog.csdn.net/qq_35419705/article/details/105694188