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

本文介绍了一种在部分排序的二维数组中查找特定整数的方法,使用分治法从左下角开始,根据数组的排序特性逐步逼近目标值,提供C++和Python实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

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

解题思路

根据题目信息,可以知道输入和输出信息如下:

  • 输入: 二维数组和待查询的整数
  • 输出: 待查询整数是否在二维数组(True, False)

已知二维数组是呈规律排列,我们可以先确定一个查询起点,再根据已知的排列规律进行查询。如将二维数组左下角元素作为查询起点,比较左下角元素与待查询数值的大小,如果左下角元素小于待查询数值,则根据排列规则,应该将列数+1。再进行比较,直到左下角元素大于待查询数值,此时即可以将行数-1。继续查询,直到左下角元素等于待查询数值,即可返回True,反之,返回False。

解题步骤

二维数组matrix, 二维数组行数: rows,二维数组列数: cols, 待查询数值num

  1. 先将二维数组转换成一维数组进行处理
  2. 定义判断初始值为左下角元素matrix[row][col],其中row=rows-1, col=0
  3. 将二维数组的左下角元素matrix[row][col](或者右上角元素)值与带查询num进行比较,如果matrix[row][col] > num,则–row;如果matrix[row][col] < num,则++col。
  4. 重复第3步,直到遍历完所有可以遍历的数组元素。

代码

分治法

C++

class Solution {
public:
    bool Find(int target, vector<vector<int> > array) {
        int matrix_rows = array.size();
        int matrix_cols = array[0].size();
        int row = matrix_rows-1;
        int col = 0;
        if(matrix_rows == 0 || matrix_cols == 0)
            return false;
        while(row >= 0 && col < matrix_cols){
            if(target == array[row][col])
                return true;
            else if(target < array[row][col])
                row--;
            else
                col++;
        }
        return false;
    }
};

Python

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

C++

bool Find(int* matrix,int rows, int columns, int number)
{
    bool Find = false;
    if(matrix != NULL && rows > 0 && columns > 0)
    {
        int rows = 0;
        int column = columns - 1;
        while(row < rows && column >= 0)
        {
            if(matrix[row * colums + column] == number)
            {
                found = true;
                break;
            }
            else if(matrix[row * colums + column] > number)
                --cloumn;
            else
                ++row;
        }
    }
    return found;
}

暴力法

#include <iostream>
#include <vector>

using namespace std;


class Solution
{
public:
    bool Find(vector<vector<int> > array,int target)
    {
        int row = 0, col = 0, t = 0;
        bool isFound = false;

        for(int i = 0; i < array.size( ) ; ++i)
        {
            for(int j = 0; j < array[i].size( ); ++j)
            {
                //边输入边验证
                if(false == isFound && target == array[i][j])
                {
                    //已经找到后就没必要再找了
                    isFound = true;
                }
            }
        }

        return isFound;

    }
};

参考

[1] https://github.com/amusi/coding-note/tree/master/Coding Interviews/03_FindInPartiallySortedMatrix
[2] https://blog.youkuaiyun.com/gatieme/article/details/51100125
[3]《剑指Offer》
[4] https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e?tpId=13&tqId=11154&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

后记

数据结构与算法是编程的基础,是程序员必备的能力。
鉴于自身编程能力有待提高,所以开始刷经典的《剑指Offer》、leetcode和各大名企面试题,顺便以优快云博客的形式做笔记,可能会借鉴很多资料,但是都会注明来源。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值