剑指offer-question4-二维数组中的查找

 题目:

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

方法:

  首先选取数组中右上角的数字。如果该数字等于要查找的数字,则查找过程结束

  如果该数字大于要查找的数字,则剔除这个数字所在列,

  如果该数字小于要查找的数字,则剔除这个数字所在行。

  也就是说,如果查找的数字不在右上角就每次都缩小范围直到查找到该数字,或者查找范围为空。

 1 package question4;
 2 
 3 import java.util.Scanner;
 4 
 5 public class Solution {
 6     public static void main(String[] args) {
 7         Scanner scan = new Scanner(System.in);
 8         
 9         int[][] matrix={{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
10         //初始化数组行数
11         int rows = matrix.length;
12         //初始化数组列数
13         int columns = matrix[0].length;
14         System.out.println("当前数组是:");
15         for(int i = 0; i < rows; i++) {
16             if(i != 0) {
17                 System.out.println("");
18             }
19             for(int j = 0; j < columns; j++) {
20                 System.out.print(matrix[i][j]+"\t");
21             }
22         }
23         
24         int found = 0;
25         System.out.println("\n" + "请输入你要查找的数字:");
26         int number;
27         number = scan.nextInt();
28         scan.close();
29         //System.out.println("test rows" + rows);
30         //System.out.println("test columns" + columns);
31         
32         if(rows > 0 && columns > 0){
33             int row = 0;
34             int column = columns - 1;
35             while(row < rows && column > 0){
36                 //System.out.println("test row" + row);
37                 //System.out.println("test column" + column);
38                 //System.out.println("test matrix[row][column]" + matrix[row][column]);
39                 
40                 if(matrix[row][column] == number){
41                     found = 1;
42                     break;
43                 }
44                 
45                 else if(matrix[row][column] < number){
46                     row++;
47                 }
48                 
49                 else
50                     column--;
51             }
52             //System.out.println("test found" + found);
53             if(found == 1) {
54                 System.out.println("数字存在" + "   " + "他的位置在第" + (row+1) +"行    第" + (column+1) + "列");
55             }
56             else if(found == 0)
57                 System.out.println("数字不存在");
58         }
59 
60     }
61 }

猜你喜欢

转载自www.cnblogs.com/diaohuluwa/p/10882655.html
今日推荐