本文主要是介绍[LeetCode] 240. Search a 2D Matrix II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题:https://leetcode.com/problems/search-a-2d-matrix-ii/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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
Example:
Consider the following 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]
]
Given target = 5, return true.
Given target = 20, return false.
思路
剑指offer中见到的一道题。从矩阵的 右上角开始探索。若当前 元素比 target小,当前行加一,若大,当前列减一。若 当前元素等于target ,返回True。若 当前 行 或 列 越界,则返回 False。
code
Your runtime beats 79.66 % of python3 submissions.
class Solution:def searchMatrix(self, matrix, target):""":type matrix: List[List[int]]:type target: int:rtype: bool"""n = len(matrix)if n ==0:return Falsem = len(matrix[0])i = 0j = m-1while not( i == n or j == -1 ):if matrix[i][j]>target:j -= 1elif matrix[i][j]<target:i += 1else:return Truereturn False
第二版 java 编写
class Solution {public boolean searchMatrix(int[][] matrix, int target) {int matRow = matrix.length;if(matRow == 0)return false;int matCol = matrix[0].length;int pr = 0;int pc = matCol -1;while(pr<matRow && pc>=0){if(matrix[pr][pc]<target)pr++;else if(matrix[pr][pc]>target)pc--;elsereturn true;}return false;}
}
这篇关于[LeetCode] 240. Search a 2D Matrix II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!