【LeetCode】74. Search a 2D Matrix

栏目: 编程工具 · 发布时间: 6年前

内容简介:【LeetCode】74. Search a 2D Matrix

问题描述

https://leetcode.com/problems/search-a-2d-matrix/#/description

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 .

算法

从左上角开始,一行一行地进行搜索,如果这一行的最后一个数小于 target ,那就移到下一行;否则,就在这一行搜索 target

参考自: https://discuss.leetcode.com/topic/29159/java-clear-solution

算法

public boolean searchMatrix(int[][] matrix, int target) {  
            if(matrix == null || matrix.length == 0) return false;
            int i = 0, j = matrix[0].length - 1;
            while(i<matrix.length && j >= 0) {
                if(matrix[i][j] == target) {
                    return true;
                } else if(matrix[i][j] < target) {
                    i++;
                } else {
                    j--;
                }
            }
            return false;
        }
转载请注明出处

http://www.zgljl2012.com/leetcode-74-search-a-2d-matrix/


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

C语言基础

C语言基础

安博教育集团 / 2012-2 / 37.00元

《C语言基础》深入浅出地介绍了C语言程序设计的基础知识,内容涉及C语言基础、算法基础、变量、数据类型、运算符、输入/输出相关函数、选择结构、循环结构、各种表达式、数组、字符串、指针、函数、结构体、ISO C99的扩展语法等。全书内容丰富,结构严谨,层次清晰,语言生动,论述精准而深刻,实例丰富而实用。 《C语言基础》不仅适合用做计算机职业培训的首选教材,也可作为普通高校教材使用,更是C语言初学......一起来看看 《C语言基础》 这本书的介绍吧!

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具