剑指01二维数组的查找

题目描述

在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
class Solution {
public:
    bool Find(int target, vector<vector<int> > array) {
        //array 是二维数组,这里没做判空操作
        int rows=array.size();
        int cols=array[0].size();
        int i=rows-1,j=0;//左下角元素坐标
        while (i>=0 && j<cols){
            //使其不超出数组范围
            if (target<array[i][j])
                i--;//查找的元素较少,往上找
            else if (target >array[i][j])
                j++;//查找的元素较大,往右找
            else
                return true;//找到
        }
        return false;
        
    }
};
public class Solution {
    public boolean Find(int target, int [][] array) {
        int rows=array.length;
        int cols=array[0].length;
        int i=rows-1,j=0;
        while (i>=0 && j<cols){
            if (target <array[i][j])
                i--;
            else if (target>array[i][j])
                j++;
            else
                return true;
        }
        return false;
    }
}
# -*- coding:utf-8 -*-
class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        rows=len(array)-1
        cols=len(array[0])-1
        i=rows
        j=0
        while j<=cols and i>=0:
            if target <array[i][j]:
                i-=1
            elif target>array[i][j]:
                j+=1
            else :
                return True
        return False
   

猜你喜欢

转载自www.cnblogs.com/hrnn/p/13401990.html