You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode 74题Search a 2D Matrix代码超时问题求助

二维矩阵搜索算法超时问题排查

我用非递归实现了二维矩阵搜索的算法,在第一个示例输入时出现超时错误,但手动推演代码时认为它应该能正常终止。

示例输入

input: [[1,3,5,7],[10,11,16,20],[23,30,34,60]]
target: 3

我的Rust代码

use std::cmp::Ordering;
use std::cmp;

impl Solution {
    pub fn search_matrix(matrix: Vec<Vec<i32>>, target: i32) -> bool {
        let m       = matrix.len();
        let n       = matrix[0].len();
        let mut min = 0; 
        let mut max = n * m - 1;
        while  min != max {
            let mid = (min + max) / 2;
            match target.cmp(&matrix[mid / n][mid % n]) {
                Ordering::Less    => max = cmp::max(0, mid - 1),
                Ordering::Equal   => return true,
                Ordering::Greater => min = cmp::min(n*m-1, mid + 1),
            }
        }
        return target == matrix[min / n][min % n];
    }
}

我曾怀疑是矩阵索引问题,尝试了所有可能的索引组合(比如[mid / m][mid % m]、[mid / n][mid % m]等),但都无效。添加min/max的边界处理也没能解决超时问题。

内容的提问来源于stack exchange,提问作者New_Caird

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 15:47:36