二维数组中的查找-剑指Offer

二维数组中的查找

题目描述

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

输入描述

  array: 待查找的二维数组

  target:查找的数字

输出描述

  查找到返回true,查找不到返回false

思路

  1. 因为数组是从左到右从上到下都是递增排序的,所以我们可以从右上角开始查找,如果右上角的数比target大,那它所在的这一列都大,可以舍去,直到找到小的,然后开始从上向下找,若右上角的比target小,那它所在的这一行都小,可以舍去,向下直到找到大于等于target的,步骤还是那样找
  2. 我们也可以从左下角开始找,道理是一样的,就是大小比较要反过来

代码

public class Solution {
public boolean Find(int [][] array,int target) {
	boolean found = false;
	if (array != null && array.length > 0 && array[0].length > 0) {
		int row = 0;
		int column = array[0].length - 1;
		while (row <= (array.length - 1) && column >= 0) {
			if (array[row][column] == target) {
				found = true;
				break;
			} else if (array[row][column] > target) {
				column--;
			} else {
				row++;
			}
		}
	}
	return found;
}
}
posted @ 2016-06-21 20:40  RosenDing  阅读(149)  评论(0编辑  收藏  举报