LeetCode: 240.Search2D(查找數字)

文章最前: 我是Octopus,這個名字來源於我的中文名--章魚;我熱愛編程、熱愛算法、熱愛開源。所有源碼在我的個人github ;這博客是記錄我學習的點點滴滴,如果您對 Python、Java、AI、算法有興趣,可以關注我的動態,一起學習,共同進步。

相關文章:

  1. LeetCode:55. Jump Game(跳遠比賽)
  2. Leetcode:300. Longest Increasing Subsequence(最大增長序列)
  3. LeetCode:560. Subarray Sum Equals K(找出數組中連續子串和等於k)

文章目錄:

題目描述:

java實現方式1:

python實現方式1:

源碼地址:https://github.com/zhangyu345293721/leetcode


題目描述:

編寫一個高效的算法來搜索 m x n 矩陣 matrix 中的一個目標值 target。該矩陣具有以下特性:

每行的元素從左到右升序排列。
每列的元素從上到下升序排列。
示例:

現有矩陣 matrix 如下:[
  [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。


著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。


java實現方式1:

package leetcodejava.top100likedquestions;

/**
 * 二維數組查找
 *
 * @author: zhangyu
 */
public class Search2D240 {
    /**
     * 輸入數據,找出目標值
     *
     * @param matrix 二維數組
     * @param target 目標值
     * @return 布爾值
     */
    public boolean searchMatrix(int[][] matrix, int target) {
        int row = matrix.length;
        if (row == 0) {
            return false;
        }
        int col = matrix[0].length;
        int i = 0;
        int j = col - 1;
        while (i < row && j >= 0) {
            if (matrix[i][j] == target) {
                return true;
            } else if (matrix[i][j] > target) {
                j--;
            } else {
                i++;
            }
        }
        return false;
    }
}

時間複雜度:O(n)

空間複雜度:O(1)


python實現方式1:

# -*- coding:utf-8 -*-
'''
author:zhangyu
date:2020/1/20
'''
from typing import List


def search_matrix(matrix: List[List[int]], target: int) -> bool:
    '''
        查找二維數組
    Args:
        matrix: 二維數組
        target: 目標值
    Returns:
        是否找到那個值
    '''
    row = len(matrix)
    if row == 0:
        return False
    col = len(matrix[0])
    i = 0
    j = col - 1
    while i < row and j >= 0:
        if matrix[i][j] == target:
            return True
        elif matrix[i][j] > target:
            j -= 1
        else:
            i += 1
    return False

時間複雜度:O(n)

空間複雜度:O(1)


源碼地址:https://github.com/zhangyu345293721/leetcode

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章