Sorting_Searching 有序矩阵中查找数 @CareerCup

本文介绍了一种高效的矩阵搜索算法,该算法适用于每一行和每一列都已排序的矩阵,通过从右上角或左下角开始查找,每次比较都能排除一行或一列,从而快速定位目标元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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



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--;
			}
		}
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值