0
点赞
收藏
分享

微信扫一扫

计算机毕业设计hadoop+spark知网文献论文推荐系统 知识图谱 知网爬虫 知网数据分析 知网大数据 知网可视化 预测系统 大数据毕业设计 机器学习

半秋L 2024-09-21 阅读 5

文章目录

搜索二维矩阵

示例 1:
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
输出:true

示例 2:
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
输出:false

我的思路

var searchMatrix = function (matrix, target) {
    if (matrix.length === 0 || matrix[0].length === 0) {
        return false;
    }
    const rows = matrix.length;
    const cols = matrix[0].length;
    for (let i = 0; i < rows; i++) {
        if (target < matrix[i][0]) {
            return false;
        }
        if (target > matrix[i][cols - 1]) {
            continue;
        }
        for (let j = 0; j < cols; j++) {
            if (matrix[i][j] === target) {
                return true;
            }
        }
    }
    return false;
};

网上思路

var searchMatrix = function(matrix, target) {
    const m = matrix.length, n = matrix[0].length;
    let low = 0, high = m * n - 1;
    while (low <= high) {
        const mid = Math.floor((high - low) / 2) + low;
        const x = matrix[Math.floor(mid / n)][mid % n];
        if (x < target) {
            low = mid + 1;
        } else if (x > target) {
            high = mid - 1;
        } else {
            return true;
        }
    }
    return false;
};

总结

很实用,正好我自身有项目在使用二维矩阵,明天我来试试

举报

相关推荐

0 条评论