TypechoJoeTheme

IT技术分享

统计

[LeetCode 74] Search a 2D Matrix [Java] [Runtime : 1MS]

2017-07-20
/
0 评论
/
589 阅读
/
正在检测是否收录...
07/20

1. 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.

2. Runtime Distribution

3. Submission Details

4. Example

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

5. Code

public class LeetCode0074 {
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return false;
        }

        int rowLength = matrix.length, col = matrix[0].length - 1;
        int row = 0;
        while(col >= 0 && row < rowLength){

            if(matrix[row][col] == target){
                return true;
            }
            if(matrix[row][col] < target){
                row ++;
            }
            else{
                col --;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        LeetCode0074 leetcode = new LeetCode0074();
        int[][] matrix = {
            {1,3,5,7},
            {10,11,16,20},
            {23,30,34,50}
        };
        System.out.println(leetcode.searchMatrix(matrix, 3));
    }
}
Array
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/592/(转载时请注明本文出处及文章链接)