-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContents.swift
94 lines (87 loc) · 2.6 KB
/
Contents.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import Foundation
/**
74. Search a 2D Matrix
Tags: Array、Binary Search
https://leetcode.com/problems/search-a-2d-matrix/description/
*/
/**
一次二分查找实现, 16ms.
假设N为矩阵中的元素数量, 时间复杂度O(logN), 空间复杂度O(1)
*/
class Solution {
func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
if matrix.count == 0 || matrix.first!.count <= 0 {
return false
}
// 边界判断
if target < matrix.first!.first! || target > matrix.last!.last! {
return false
}
// 因为矩阵的每行都有序, 可将矩阵看作"一个数组"进行二分查找
var low = 0
var high = matrix.count * matrix.first!.count - 1
var mid = 0
while low <= high {
mid = (low + high) / 2
// index转换为坐标
let row = mid / matrix.first!.count
let column = mid % matrix.first!.count
let value = matrix[row][column]
if value == target {
return true
} else if target < value {
high = mid - 1
} else {
low = mid + 1
}
}
return false
}
}
/**
两次二分查找实现, 20ms
假设矩阵有N行, 每行M列, 时间复杂度O(logN + logM), 空间复杂度O(1)
*/
class SolutionBrute {
func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
if matrix.count == 0 || matrix.first!.count <= 0 {
return false
}
// 边界判断
if target < matrix.first!.first! || target > matrix.last!.last! {
return false
}
// 二分查找确认行
var rowLow = 0
var rowHigh = matrix.count - 1
var row = 0
while rowLow <= rowHigh {
row = (rowLow + rowHigh) / 2
let rowMin = matrix[row].first!
let rowMax = matrix[row].last!
if target >= rowMin && target <= rowMax {
break
} else if target < rowMin {
rowHigh = row - 1
} else {
rowLow = row + 1
}
}
// 行中二分查找确定是否存在
var low = 0
var high = matrix[row].count - 1
var mid = 0
while low <= high {
mid = (low + high) / 2
let value = matrix[row][mid]
if target == value {
return true
} else if target < value {
high = mid - 1
} else {
low = mid + 1
}
}
return false
}
}