已排序数字矩阵中查找某个数(百度面试题)

已知一个按行和按列都是增序的数字矩阵,如何快速查找某个数x是否在矩阵中?


思路其实比较简单,只要利用好第一排的数比第二排对应位置的数小,第一列的数比第二列对应位置的数小这一规律就行。


/**
 * 快速在一个按行和按列都是增序的数字矩阵查找某个数
 * 
 * @author cui
 *
 */
public class MatrixSelect {
	public static void main(String[] args) {
		int[][] input = { 
				{ 1, 4, 7, 11, 15 }, 
				{ 2, 5, 8, 12, 19 }, 
				{ 3, 6, 9, 16, 22 }, 
				{ 10, 13, 14, 17, 24 },
				{ 18, 21, 23, 26, 30 }
				};
		select(input,1);//found 1 in (0,0)
		select(input,5);//found 5 in (1,1)
		select(input,17);//found 17 in (3,3)
		select(input,30);//found 30 in (4,4)
		select(input,-1);//not found -1
		select(input,20);//not found 20
		select(input,50);//not found 50
	}
	
	public static void select(int[][] m, int target) {
		int row = 0, col = m[0].length-1;
		while (col >= 0 && row < m.length) {
			int cur=m[row][col];
			if(cur==target){
				System.out.println("found " + target+" in ("+row+","+col+")");
				return;
			}else if(cur>target){
				col--;
			}else if(cur<target){
				row++;
			}
		}
		System.out.println("not found " + target);
	}
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值