题目
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
解题思路:
首先选取数组中右上角的数字。如果该数字等于要查找的数字,查找过程结束;如果该数字大于要查找的数字,剔除这个数字所在的列;如果该数字小于要查找的数字,剔除这个数字所在的行。
代码
/** * */package com.jason.interviewQuestions.basicKnowledge;/** * 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 * @author jason zhang * */public class FindInPartiallySortedMatirx { /** * 从右上角开始查找 * @param matirx 被查找的数组 * @param rows 数组的行数 * @param columns 数组的列数 * @param number 查找的数字 * @return */ boolean findFromUpperRight(int[][] matrix, int rows, int columns, int number) { boolean found = false; if (matrix != null && rows > 0 && columns > 0) { int row = 0; int column = columns - 1; while (row < rows && column >= 0) { if (matrix[row][column] == number) { found = true; System.out.println("find the number at " + (row+1) + " row and " + (column+1) + " column"); break; } else if (matrix[row][column] > number) { //右上角的数字大于要查找的数字,剔除这个数字所在的列 column--; } else { //右上角的数字小于要查找的数字,剔除这个数字所在的行 row++; } } } return found; } /** * 从左下角开始查找 * @param matirx 被查找的数组 * @param rows 数组的行数 * @param columns 数组的列数 * @param number 查找的数字 * @return */ boolean findFromLeftLower(int[][] matrix, int rows, int columns, int number) { boolean found = false; if (matrix != null && rows > 0 && columns > 0) { int row = rows - 1; int column = 0; while (row >= 0 && column < columns) { if (matrix[row][column] == number) { found = true; System.out.println("find the number at " + (row+1) + " row and " + (column+1) + " column"); break; } else if (matrix[row][column] > number) { //左下角的数字大于要查找的数字,剔除这个数字所在的行 row--; } else { //左下角的数字小于要查找的数字,剔除这个数字所在的列 column++; } } } return found; }}
测试代码
package com.jason.interviewQuestions.basicKnowledge;import junit.framework.TestCase;public class FindInPartiallySortedMatirxTest extends TestCase { private FindInPartiallySortedMatirx fipsm; private int[][] matrix = { {1,2,8,9}, {2,4,9,12}, {4,7,10,13}, {6,8,11,15} };; protected void setUp() throws Exception { super.setUp(); this.fipsm = new FindInPartiallySortedMatirx(); } public void testFindFromUpperRight() { int number = 15; boolean find = this.fipsm.findFromUpperRight(matrix, 4, 4, number); super.assertTrue(find); } public void testFindFromUpperRightNF() { int number = 3; boolean find = this.fipsm.findFromUpperRight(matrix, 4, 4, number); super.assertFalse(find); } public void testfindFromLeftLower() { int number = 7; boolean find = this.fipsm.findFromUpperRight(matrix, 4, 4, number); super.assertTrue(find); } public void testfindFromLeftLowerNF() { int number = 3; boolean find = this.fipsm.findFromUpperRight(matrix, 4, 4, number); super.assertFalse(find); }}
备注:
题目来自于何海涛著的《剑指offer》,书中使用c实现,本文使用java实现。