原文:
Given a matrix in which each row and each column is sorted, write a method to find an element in it.
译文:
给出一个矩阵,其中每一行和每一列都是有序的,写一个函数在矩阵中找出指定的数。
矩阵是有序的,因此要利用这一点,当矩阵中元素和要查找的元素对比后, 如果相等,我们返回下标;如果不等,我们就排除掉一些元素,而不仅仅是对比的元素。 我们从矩阵的四个角的元素入手看看,有什么特点。左上角是最小的, 因为矩阵向右是递增的,向下也是递增的。同理,右下角是最大的。让我们来看看右上角, 设要查找的元素为x,比如x比右上角元素5大,那么它也会比第一行的其它元素都大。 因此可以去掉第一行;如果它比右上角元素小,那么它也会比最后一列的元素都小, 因此可以去掉最后一列;然后这样不断地比下去,只需要O(m+n)的时间就查找完。 对于左下角的元素,也有一样的特点。就不再分析了。
package chapter_9_SortingandSearching;
import java.util.Scanner;
/**
*
* 给出一个矩阵,其中每一行和每一列都是有序的,写一个函数在矩阵中找出指定的数。
*
*/
public class Question_9_6 {
/**
* @param array
* @param find
* @return
*
* 可以从右上角开始查找,右上角数组是所在行最大,所在列最小
* 如果等于,则直接找到返回。
* 如果小于右上角数字,则当前最后一列可以排除。因为最后一列从上向下递增
* 如果大于右上角数字,则当前第一行可以排除。因为第一行左往右递增。
*
*/
public static int findIndex(int array[][], int find) {
int row = 0;
int col = array[0].length -1;
while(row < array.length && col >= 0) {
if(array[row][col] > find) {
col --;
} else if(array[row][col] < find) {
row ++;
} else {
return row * array[0].length + col;
}
}
return -1;
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int row = scanner.nextInt();
int col = scanner.nextInt();
int array[][] = new int[row][col];
scanner.nextLine();
for(int i=0; i< row; i++) {
for(int j=0; j<col; j++) {
array[i][j] = scanner.nextInt();
}
scanner.nextLine();
}
int find = scanner.nextInt();
int index = findIndex(array, find);
System.out.println("index x:" + index/array[0].length + " y:" + index%array[0].length);
}
}