剑指offer66题--Java实现,c++实现和python实现 1.二维数组中的查找

题目描述

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

Java的实现

public class Solution {
    public boolean Find(int target, int [][] array) {

        int rows=array.length;//获取数组行数
        int cols=array[0].length;//获取数组列数
        if(array!=null)//如果数组不为空
        {
            int row=0;//右上角行坐标
            int col=cols-1;//右上角列坐标
            while(row<rows&&col>=0)//循环条件
            {
                if(target==array[row][col])//如果右上角的数等于要查找的数
                    return true;
                else if(target<array[row][col])//如果右上角的数大于要查找的数,则不要这一列
                    --col;//列坐标减一
                else//如果右上角的数小于要查找的数,则不要这一行
                    row++;//行坐标加一
            }
        }
        return false;
        
    }
}

C ++实现

class Solution {
public:
    bool Find(int target, vector<vector<int> > array) {
        //行列个数
        int rows=array.size();
        int cols=array[0].size();
        if(!array.empty())
        {
            //右上角坐标
            int row=0;
            int col=cols-1;
            while(row<rows&&col>=0)
            {
                if(target==array[row][col])
                return true;
                else if(target<array[row][col])
                    --col;
                else
                    ++row;
            }
        }
        return false;
            
    }
};

python实现

# -*- coding:utf-8 -*-
class Solution:
    # array 二维列表
    def Find(self, target, array):
       
        rows=len(array)#数组行数
        cols=len(array[0])#数组列数
        row=0#行下标
        col=cols-1#列下标
        while row<rows and col>=0:#从右上角遍历数组
            if(target>array[row][col]):
                row+=1
            elif target==array[row][col]:
                return True
            else:
                col-=1
        return False
        
        # write code here

猜你喜欢

转载自blog.csdn.net/walter7/article/details/83990530