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

剑指offer算法 java实现

题目:

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

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


1  2  8  9

2  4  9  12

4  7  10  13

6  8  11  15


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


[java]  view plain  copy
  1. package com.ynu.www.offer;    
  2.     
  3. public class FindFromMatrix {    
  4.     
  5.     private static int[][] sample = new int[][] { { 1289 },    
  6.             { 24912 }, { 471013 }, { 681115 } };    
  7.     
  8.     public static void printSample() {    
  9.         for (int i = 0; i < sample.length; i++) {    
  10.             for (int j = 0; j < sample[i].length; j++) {    
  11.                 System.out.print(sample[i][j] + " ");    
  12.             }    
  13.             System.out.println();    
  14.         }    
  15.     }    
  16.     
  17.     public static boolean getValuefromMatrix(int[][] sample, int rows,    
  18.             int columns, int num) {    
  19.         boolean found = false;    
  20.         if (sample != null && rows > 0 && columns > 0) {    
  21.             int row = 0;    
  22.             int column = columns - 1;    
  23.             while (row < rows && column >= 0) {    
  24.                 int tempValue = sample[row][column];    
  25.                 if (num > tempValue) {    
  26.                     ++row;    
  27.                 } else if (num < tempValue) {    
  28.                     --column;    
  29.                 } else {    
  30.                     found = true;    
  31.                     break;    
  32.                 }    
  33.             }    
  34.         }    
  35.     
  36.         return found;    
  37.     }    
  38.     
  39.     public static void main(String[] args) {    
  40.         printSample();    
  41.         System.out.println(getValuefromMatrix(sample, 447));    
  42.     
  43.     }    
  44. }  



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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值