Leetcode240 Search a 2D Matrix II
题目描述
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 | [ |
Given target = 5
, return true
.
Given target = 20
, return false
.
思路
两个指针,一个控制row,一个控制column,因为整个Matrix是有序的,则如果该数比最后一个column(即每一行最大的数)小,则column指针向左移动,如果该数比第一个row大(即每一行最小的数)则row指针向下移动。
代码
1 | class Solution { |