• 240. Search a 2D Matrix II&&74. Search a 2D Matrix 都用不严格递增的方法


    一句话思路:从左下角开始找。复杂度是o(m+n)。

    一刷报错:

    1. 应该是一个while循环中有几个条件判断语句,而不是每个条件判断语句里去加while,很麻烦 
    2. 数组越界了。从0开始,y的最大条件应该是<n,不是《n
    3. 风格上:++ -- 都是一个数字的一元运算,不用加空格
    4. 超时了。循环体结构:
            while (x >= 0 && y <= n) {
                if (matrix[x][y] == target) {
                    count ++;
                }
                else if (matrix[x][y] > target) {
                    x --;
                }
                else if(matrix[x][y] < target) {
                    y ++;
                }
                else {
                    x --;
                    y ++;
                }
            }

    错误的原因在于:没有意识到这个矩阵可以是不严格单调递增的,在最左一列、最下一行找到后,继续朝右上方找,还有可能找到。

    一句话总结:注意不严格单调递增的特点,在边界线上找到后还要继续找。而且还要注意不要数组越界。(有0时写小于号)

    class Solution {
        public int searchMatrix(int[][] matrix, int target) {
            
            if (matrix == null || matrix.length == 0) {
                return 0;
            }
            if (matrix[0] == null || matrix[0].length == 0) {
                return 0;
            }
            
            int m = matrix.length;
            int n = matrix[0].length;
            int x = m - 1;
            int y = 0;
            int count = 0;
            
            while (x >= 0 && y < n) {
                if (matrix[x][y] > target) {
                    x--;
                }
                else if(matrix[x][y] < target) {
                    y++;
                }
                else {
                    count++;
                    x--;
                    y++;
                }
            }
             
            //if (count > 0) {
              //  return true;
            //}
            return count;
        }
    }
  • 相关阅读:
    贝叶斯定理
    用matplotlib统计数据并画图
    词云图
    一行python代码能写出啥?
    用python生成二维码
    18个python的高效编程技巧
    django简介
    vue点击变色
    selenium破解人人登陆验证码
    selenium请求豆瓣网
  • 原文地址:https://www.cnblogs.com/immiao0319/p/7885660.html
Copyright © 2020-2023  润新知