|
1 | 1 | /// [Leetcode](https://leetcode.cn) solution
|
2 | 2 | pub struct Solution;
|
3 | 3 |
|
4 |
| -use std::collections::{HashMap, VecDeque}; |
| 4 | +use std::{ |
| 5 | + cmp::Ordering, |
| 6 | + collections::{HashMap, VecDeque}, |
| 7 | +}; |
5 | 8 |
|
6 | 9 | impl Solution {
|
7 | 10 | /// [1. Tow Sum](https://leetcode.cn/problems/two-sum/description)
|
@@ -1107,4 +1110,48 @@ impl Solution {
|
1107 | 1110 | }
|
1108 | 1111 | }
|
1109 | 1112 | }
|
| 1113 | + |
| 1114 | + /// [240. Search a 2D Matrix II](https://leetcode.cn/problems/search-a-2d-matrix-ii/description) |
| 1115 | + /// |
| 1116 | + /// Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties: |
| 1117 | + /// |
| 1118 | + /// Integers in each row are sorted in ascending from left to right. |
| 1119 | + /// Integers in each column are sorted in ascending from top to bottom. |
| 1120 | + /// |
| 1121 | + /// Example 1: |
| 1122 | + /// |
| 1123 | + /// Input: 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 |
| 1124 | + /// Output: true |
| 1125 | + /// |
| 1126 | + /// Example 2: |
| 1127 | + /// |
| 1128 | + /// Input: 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 = 20 |
| 1129 | + /// Output: false |
| 1130 | + /// |
| 1131 | + /// Constraints: |
| 1132 | + /// |
| 1133 | + /// m == matrix.length |
| 1134 | + /// n == matrix[i].length |
| 1135 | + /// 1 <= n, m <= 300 |
| 1136 | + /// -10^9 <= matrix[i][j] <= 10^9 |
| 1137 | + /// All the integers in each row are sorted in ascending order. |
| 1138 | + /// All the integers in each column are sorted in ascending order. |
| 1139 | + /// -10^9 <= target <= 10^9 |
| 1140 | + pub fn search_matrix(matrix: Vec<Vec<i32>>, target: i32) -> bool { |
| 1141 | + if matrix.is_empty() { |
| 1142 | + return false; |
| 1143 | + } |
| 1144 | + |
| 1145 | + let (m, n) = (matrix.len(), matrix[0].len()); |
| 1146 | + let (mut x, mut y) = (0, n - 1); |
| 1147 | + while x < m && y < n { |
| 1148 | + let value = matrix[x][y]; |
| 1149 | + match value.cmp(&target) { |
| 1150 | + Ordering::Equal => return true, |
| 1151 | + Ordering::Less => x = x + 1, |
| 1152 | + Ordering::Greater => y = y - 1, |
| 1153 | + } |
| 1154 | + } |
| 1155 | + return false; |
| 1156 | + } |
1110 | 1157 | }
|
0 commit comments