01 二维数组中的查找

题目描述

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

题解:

public static void find(int target,int[][]array){
	if(array == null || array.length == 0 || array[0].length == 0)
		return false;
	int rows = array.length;
	int cols = array[0].length;
	int row = 0,col = cols - 1;
	while(row >= 0 && row < rows && col >=0 && col < cols){
		if(array[row][col] == target){
			return true;
		}else if(array[row][col] < target){
			row++;
		}else{
			col--;
		}
	}
	return false;
}

牛客网地址:https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e?tpId=13&tqId=11154&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

小结:

  • 当传入数组时,需要判空,逻辑如下:

    if(array == null || array.length == 0 || array[0].length == 0)
    		return false;
    
  • 该方法的时间复杂度为o(m+n)

posted @ 2019-12-02 19:15  烟云123  阅读(144)  评论(0编辑  收藏  举报