LeetCode 74 Search a 2D Matrix(搜索2D矩阵)

简介: 版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50776497 翻译写一个高效算法用于在一个m x n的矩阵中查找一个值。
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50776497

翻译

写一个高效算法用于在一个m x n的矩阵中查找一个值。
这个矩阵有如下属性:

每行的整型数都是从左到右排序的。
每行的第一个元素都比上一行的最后一列大。

例如,
考虑如下矩阵:
[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
给定target = 3,返回true

原文

Write an efficient algorithm that searches for a value in an m x n matrix. 
This matrix has the following properties:

Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
Given target = 3, return true.

分析

可能因为我好困了,所以不论是算法还是我自己,都效率很低……

下面这个代码也是一改再改……

bool searchMatrix(vector<vector<int>>& matrix, int target) {
    if (matrix[0][0] > target) return false;
    for (int i = 0; i < matrix.size(); ) {
        for (int j = 0; j < matrix[i].size(); ) {
            if (i == matrix.size() - 1 && matrix[i][j] < target) {
                if (j >= matrix[i].size()) return false;
                j += 1;
                if (matrix[i][j] > target) return false;
            }
            else if (matrix[i][j] < target && matrix[i+1][j] > target) {
                j += 1;
                if (j >= matrix[i].size()) return false;
                if (matrix[i][j] > target) return false;
            }
            else if (matrix[i][j] < target && matrix[i + 1][j] <= target) {
                i += 1;
            }
            else if (matrix[i][j] == target) {
                return true;
            }     
            if (i == matrix.size() - 1 && j == matrix[i].size() ) {
                return false;
            }
        }
    }
    return false;
}

明天再整理整理思路重新做一遍吧……

目录
相关文章
|
1月前
|
算法
力扣240 搜索二维矩阵II
力扣240 搜索二维矩阵II
|
3月前
|
算法 测试技术 C#
【二分查找】LeetCode1970:你能穿过矩阵的最后一天
【二分查找】LeetCode1970:你能穿过矩阵的最后一天
|
3月前
leetcode-329:矩阵中的最长递增路径
leetcode-329:矩阵中的最长递增路径
23 0
|
1月前
|
机器学习/深度学习 人工智能 算法
LeetCode刷题--- 面试题 01.07. 旋转矩阵(原地旋转+翻转替旋转)
LeetCode刷题--- 面试题 01.07. 旋转矩阵(原地旋转+翻转替旋转)
|
3月前
|
算法
【Leetcode 74】搜索二维矩阵 —— 二分查找|矩阵
给你一个满足下述两条属性的`m x n`整数矩阵:每行中的整数从左到右按非严格递增顺序排列。每行的第一个整数大于前一行的最后一个整数
|
3月前
|
算法 测试技术 C#
【map】【动态规划】LeetCode2713:矩阵中严格递增的单元格数
【map】【动态规划】LeetCode2713:矩阵中严格递增的单元格数
|
3月前
leetcode-566:重塑矩阵
leetcode-566:重塑矩阵
17 0
|
3月前
leetcode-1582:二进制矩阵中的特殊位置
leetcode-1582:二进制矩阵中的特殊位置
19 0
|
30天前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
1月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记