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

已知条件:1. 二维数组行数和列数相同; 2. 每一行从左到右,每一列从上到下递增;

解题思路:选取左下角或右上角的数组元素:1. 选取左下角元素,当 target 大于 左下角元素时,列数加1;当 target 小于左下角元素时,行数减1;2. 选取右上角元素, 当 target 小于右上角元素时,列数减1;当 target 大于右上角元素时,行数加1;以左下角元素为例,代码如下:

 1 import java.util.Scanner;
 2 
 3 public class Solution {
 4     public static void main(String[] args) {
 5         Scanner scanner = new Scanner(System.in);
 6         int n = scanner.nextInt();
 7         int [][] array = new int[n][n];
 8         scanner.nextLine(); 
 9         //用来跳过行列后的回车符
10         for(int i=0 ; i<n ; i++) {
11             String [] str = scanner.nextLine().split(" ");
12             for(int j=0 ; j<str.length ; j++) {
13                 array[i][j] = Integer.parseInt(str[j]);
14             }
15         }
16         int target = scanner.nextInt();
17         boolean result = Find(target, array);
18         System.out.println(result);
19     }
20 
21     public static boolean Find(int target, int [][] array) {
22         // 解题思路:二维数组每一行和每一列都是递增的,取左下角或右上角的元素与target进行对比
23         // 以左下角为例
24         int row = array.length-1;
25         int col = 0;
26         while(row >= 0 && col <= array[0].length-1) {
27             if(array[row][col] == target)
28                 return true;
29             else if(array[row][col] > target)
30                 row--;
31             else
32                 col++;
33         }
34         return false;
35     }
36 }        
原文地址:https://www.cnblogs.com/maxge/p/12805810.html