Wins the offer-45. Finding two-dimensional array (44)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_38332722/article/details/100586943

45. Find a two-dimensional array (44)

  • Description Title: (same as the length of each one-dimensional array) in a two-dimensional array, each row from left to right in order of ascending sort, to sort each column from top to bottom in increasing order. A complete function, enter such a two-dimensional array and an integer, it is determined whether the array contains the integer.

  • Ideas:

  • Code:

    package _45.二维数组的查找;
    /**
     * 
     * @author Administrator
     *
     */
    public class FindInPartiallySortedMatrix {
        public static boolean find(int target, int [][] array) {
        	if(array == null || array.length == 0 || array[0].length == 0) return false;
        	
        	int row = 0;
        	int rows = array.length;
        	int column = array[0].length - 1;
        	//从右上角开始查找
        	while((column >= 0) && (row < rows)){
        		if(array[row][column] == target){
        			return true;
        		}
        		else if(array[row][column] > target){
        			column--;
        		}
        		else{
        			row++;
        		}
        	}
        	return false;
        }
        
        public static void main(String[] args) {
        	int[][] data = {{1,2,8,9},
                    {2,4,9,12},
                    {4,7,10,13},
                    {6,8,11,15}};
        	boolean find = find(11,data);
        	System.out.println(find);
    	}
    }
    

Guess you like

Origin blog.csdn.net/qq_38332722/article/details/100586943