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

本文介绍了一种在特殊排序的二维数组中查找特定整数的高效算法。通过对比目标值与数组右上角元素,逐步缩小搜索范围,实现快速查找。文章提供了详细的解题思路和完整的Java代码实现。

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

剑指offer–二维数组中的查找

题目描述

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

解题思路

选取右上角元素,target 大于array[i][j], 则剔除整行;

        target 小于array[i][j],则删除整列;

public boolean Find(int target, int [][] array)

解题思路
注意:

     1.我们在选取第一个数来与target比较大小时,一定要选取数组中最靠边的数也就是每行每列最后一个数。因为这样在比较大小时,在选取第二个数比较时不会出现冲突。

     2.在比较前可以判断数组是否为空,查找的这个数是否在数组中。

主程序代码Solution:

public class Solution {
	public boolean Find(int target, int [][] array) {
 	int row = array.length;
	//cannot be col = array[1].length, in case array is empty
	int col = array[0].length;
	if (row <= 0 || col <= 0) {
		return false;
	 }
  	if (target < array[0][0] || target > array[row-1][col-1]) {
   		return false;
  	}
  
	int i = 0;
	int j = col-1;
	while (i < row && j > 0) {
		if (target > array[i][j]) {
    			i++;
   		}
      		if (target < array [i][j]) {
			 j--;
   		}
 		if (target == array[i][j]) {
 			return true;
 		}
	 } 
  return false;
	 }
}

测试代码:

public class Test {
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  //test case1: {{1,2,8,9},{4,7,10,13}} find 7
  // test case2: {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}} find 5
  int array[][] = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
  // test case3: {{}} find 16
  int array1 [][] = {{}};
  Solution solution = new Solution();
  boolean temp = solution.Find(5, array);
  System.out.println(temp);

 boolean temp 1= solution.Find(16, array1);
 System.out.println(temp1);
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值