Skip to content

Commit b45e086

Browse files
author
Yi Gu
committed
[Search] Add solutions to Search 2D Matrix I and II
1 parent 52c662c commit b45e086

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

Diff for: Search/Search2DMatrix.swift

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/search-a-2d-matrix/
3+
* Primary idea: Search col and then binary search row
4+
*
5+
* Time Complexity: O(log(m + n), Space Complexity: O(1)
6+
*/
7+
8+
class Search2DMatrix {
9+
func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
10+
if matrix.count == 0 || matrix[0].count == 0 {
11+
return false
12+
}
13+
14+
let rowNum = searchRow(matrix, target)
15+
return searchCol(matrix[rowNum], target)
16+
}
17+
18+
private func searchRow(_ matrix: [[Int]], _ target: Int) -> Int {
19+
var left = 0, right = matrix.count - 1
20+
21+
while left + 1 < right {
22+
let mid = (right - left) / 2 + left
23+
if matrix[mid][0] == target {
24+
return mid
25+
} else if matrix[mid][0] < target {
26+
left = mid
27+
} else {
28+
right = mid
29+
}
30+
}
31+
32+
return matrix[right][0] <= target ? right : left
33+
}
34+
35+
private func searchCol(_ nums: [Int], _ target: Int) -> Bool {
36+
var left = 0, right = nums.count - 1
37+
38+
while left <= right {
39+
let mid = (right - left) / 2 + left
40+
if nums[mid] == target {
41+
return true
42+
} else if nums[mid] < target {
43+
left = mid + 1
44+
} else {
45+
right = mid - 1
46+
}
47+
}
48+
49+
return false
50+
}
51+
}

Diff for: Search/Search2DMatrixII.swift

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/search-a-2d-matrix-ii/
3+
* Primary idea: Start from last element at first row, then move downwards or backwards
4+
*
5+
* Time Complexity: O(m + n), Space Complexity: O(1)
6+
*/
7+
8+
class Search2DMatrixII {
9+
func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
10+
guard matrix.count > 0 else {
11+
return false
12+
}
13+
14+
var row = 0, col = matrix[0].count - 1
15+
16+
while row < matrix.count && col >= 0 {
17+
if matrix[row][col] == target {
18+
return true
19+
} else if matrix[row][col] < target {
20+
row += 1
21+
} else {
22+
col -= 1
23+
}
24+
}
25+
26+
return false
27+
}
28+
}

0 commit comments

Comments
 (0)