• 240 Search a 2D Matrix II 搜索二维矩阵 II


    编写一个高效的算法来搜索 m x n 矩阵中的一个目标值。该矩阵具有以下特性:
        每行的元素从左到右升序排列。
        每列的元素从上到下升序排列。
    例如,
    考虑下面的矩阵:
    [
      [1,   4,  7, 11, 15],
      [2,   5,  8, 12, 19],
      [3,   6,  9, 16, 22],
      [10, 13, 14, 17, 24],
      [18, 21, 23, 26, 30]
    ]
    给定目标值 target = 5, 返回 true。
    给定目标值 target = 20, 返回 false。
    详见:https://leetcode.com/problems/search-a-2d-matrix-ii/description/

    Java实现:

    class Solution {
        public boolean searchMatrix(int[][] matrix, int target) {
            if (matrix.length == 0 || matrix[0].length == 0) {
                return false;
            }
            int row=matrix.length;
            int col=matrix[0].length;
            int i=row-1;
            int j=0;
            while(i>=0&&j<col){
                if(target>matrix[i][j]){
                    ++j;
                }else if(target<matrix[i][j]){
                    --i;
                }else{
                    return true;
                }
            }
            return false;
        }
    }
    

     C++实现:

    class Solution {
    public:
        bool searchMatrix(vector<vector<int>>& matrix, int target) {
            if(matrix.empty()||matrix[0].empty())
            {
                return false;
            }
            int row=matrix.size();
            int col=matrix[0].size();
            int i=row-1;
            int j=0;
            while(i>=0&&j<col)
            {
                if(target>matrix[i][j])
                {
                    ++j;
                }
                else if(target<matrix[i][j])
                {
                    --i;
                }
                else
                {
                    return true;
                }
            }
            return false;
        }
    };
    
  • 相关阅读:
    优化SQL查询:如何写出高性能SQL语句
    提高SQL执行效率的16种方法
    Spring Ioc DI 原理
    java内存泄漏
    转:js闭包
    LeetCode Best Time to Buy and Sell Stock III
    LeetCode Best Time to Buy and Sell Stock with Cooldown
    LeetCode Length of Longest Fibonacci Subsequence
    LeetCode Divisor Game
    LeetCode Sum of Even Numbers After Queries
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8760106.html
Copyright © 2020-2023  润新知