剑指offer(2)

题目:

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

比如以下的二维数组就是每行、每列都是递增顺序,假设在这个数组中查找数字7。则返回true。假设查找数字5,因为数组中不含有该数字。则返回false。

1   2   8   9

2  4   9   12

4  7  10   13

6  8   11   15

public class FindFromMatrix {
	
	private static int[][] arr = new int[][] {  
		{ 1, 2, 8,  9  }, 
		{ 2, 4, 9,  12 }, 
		{ 4, 7, 10, 13 }, 
		{ 6, 8, 11, 15 } 
	};
	
	public static void main(String[] args) {
		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr[i].length; j++) {
				System.out.print(arr[i][j] + " ");
			}
			System.out.println();
		}
		System.out.println(find(arr, 4, 4, 7));  
	}

	public static boolean find(int[][] arr, int rows, int columns, int target) {
		boolean found = false;
		if (arr != null && rows > 0 && columns > 0) { 
			int row = 0;
			int column = columns - 1;
			while (row < rows && column >= 0) {
				int tmp = arr[row][column - 1]; // 从右上角元素開始匹配
				if (target > tmp) {
					row++; // 目标元素较大。元素不可能在当前行,行递增
				} else if (target < tmp) {
					column--; // 目标元素较小,元素不可能在当前列,列递减
				} else {
					found = true; // 找到了,返回true
					break;
				}
			}
		}
		return found;
	}
}
解题方法:从数组的右上角開始查找。这种话能够不断的缩小查找的范围,直到找到目标元素。

总结:当我们解决一个问题的时候,一个非常有效的方法就是从一个详细的问题入手,通过分析简单的样例。有时候能够找到普遍的规律。

【推广】 免费学中医,健康全家人
原文地址:https://www.cnblogs.com/yjbjingcha/p/8391474.html