二维数组中的查找

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

 1 # -*- coding:utf-8 -*-
 2 class Solution:
 3     # array 二维列表
 4     def Find(self, target, array):
 5         row = len(array)
 6         column = len(array[0])
 7         i,j = 0,column-1
 8         while i < row and j >= 0:
 9             if array[i][j] == target:
10                 return True
11             elif array[i][j] > target:
12                 j -= 1
13             else:
14                 i += 1
15         return False
16         # write code here

从右上角开始查询,其同行的元素,左边小右边大。其同列的元素,上边小下边大。

 

leetcode地址,Java版本代码:

 1 class Solution {
 2     public boolean findNumberIn2DArray(int[][] matrix, int target) {
 3         int row = matrix.length;
 4         if(row == 0){
 5             return false;
 6         }
 7         int column = matrix[0].length;
 8         int i = 0;
 9         int j = column - 1;
10         while(i < row && j>= 0) {
11             int current = matrix[i][j];
12             if(current == target) {
13                 return true;
14             }
15             else if(current > target) {
16                 j -= 1;
17             }
18             else {
19                 i += 1;
20             }
21         }
22         return false;
23     }
24 }

力扣的验证数据更加完善,注意红色的代码,对空数组的检验。

posted on 2019-06-12 21:59  Sempron2800+  阅读(102)  评论(0编辑  收藏  举报