剑指offer算法 java实现 二维数组中的查找

本文介绍如何使用Java实现一个算法,在给定的二维数组中查找指定整数,数组特性为行和列均按递增排序。通过分析特定例子,找到通用解决方法。

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

剑指offer算法 java实现

题目:

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

例如下面的二维数组就是每行、每列都是递增排序。如果在这个数组中查找数字7,则返回true,如果查找数组5,由于数组中不含有该数字,则返回false。


1  2  8  9

2  4  9  12

4  7  10  13

6  8  11  15


当我们解决一个问题的时候,一个很有效的方法就是从一个具体的问题入手,通过分析简单具体的例子,试图寻找普遍的规律。


package com.ynu.www.offer;  
  
public class FindFromMatrix {  
  
    private static int[][] sample = new int[][] { { 1, 2, 8, 9 },  
            { 2, 4, 9, 12 }, { 4, 7, 10, 13 }, { 6, 8, 11, 15 } };  
  
    public static void printSample() {  
        for (int i = 0; i < sample.length; i++) {  
            for (int j = 0; j < sample[i].length; j++) {  
                System.out.print(sample[i][j] + " ");  
            }  
            System.out.println();  
        }  
    }  
  
    public static boolean getValuefromMatrix(int[][] sample, int rows,  
            int columns, int num) {  
        boolean found = false;  
        if (sample != null && rows > 0 && columns > 0) {  
            int row = 0;  
            int column = columns - 1;  
            while (row < rows && column >= 0) {  
                int tempValue = sample[row][column];  
                if (num > tempValue) {  
                    ++row;  
                } else if (num < tempValue) {  
                    --column;  
                } else {  
                    found = true;  
                    break;  
                }  
            }  
        }  
  
        return found;  
    }  
  
    public static void main(String[] args) {  
        printSample();  
        System.out.println(getValuefromMatrix(sample, 4, 4, 7));  
  
    }  
}



根据分析,我们每次都选取数组查找范围的右上角数字,同样,我们可以选取左下角的数字,但是我们不能选择左上角或者右下角,因为无法缩小查找范围。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值