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