Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

Sorting_Searching 有序矩阵中查找数 @CareerCup

$
0
0

要点就是从右上角或者左下角开始找,每次比较能排除一行或者一列



package Sorting_Searching;

import CtCILibrary.AssortedMethods;

/**
 * 
 *Given a matrix in which each row and each column is sorted, write a method to find an element in it.

译文:

给出一个矩阵,其中每一行和每一列都是有序的,写一个函数在矩阵中找出指定的数。
 */
public class S11_6 {

	public static void main(String[] args) {
		int M = 10;
		int N = 5;
		int[][] matrix = new int[M][N];
		for (int i = 0; i < M; i++) {
			for (int j = 0; j < N; j++) {
				matrix[i][j] = 10 * i + j;
			}
		}

		AssortedMethods.printMatrix(matrix);

		for (int i = 0; i < M; i++) {
			for (int j = 0; j < M; j++) {
				int v = 10 * i + j;
				System.out.println(v + ": " + findElement(matrix, v));
			}
		}

	}
	
	public static boolean findElement(int[][] matrix, int elem) {
		int cols = matrix[0].length;
		int rows = matrix.length;
		int x = 0;				// the first row
		int y = cols-1;			// the last col
		
		while(true){
			if(x<0 || x>=rows || y<0 || y>=cols){
				return false;
			}
			if(matrix[x][y] == elem){
				return true;
			}
			if(elem > matrix[x][y]){		// 大的话,往下走
				x++;
			}
			else if(elem < matrix[x][y]){		// 小的话,往左走
				y--;
			}
		}
	}

}


作者:hellobinfeng 发表于2013-11-30 2:20:37 原文链接
阅读:55 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>