题: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 False
m = len(matrix[0])
i = 0
j = m-1
while not( i == n or j == -1 ):
if matrix[i][j]>target:
j -= 1
elif matrix[i][j]<target:
i += 1
else:
return True
return 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--;
else
return true;
}
return false;
}
}

236

被折叠的 条评论
为什么被折叠?



