forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SearchForARange.swift
64 lines (55 loc) · 1.68 KB
/
SearchForARange.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
/**
* Question Link: https://leetcode.com/problems/search-for-a-range/
* Primary idea: Binary Search, check left or right separately
*
* Time Complexity: O(logn), Space Complexity: O(1)
*/
class SearchForARange {
func searchRange(nums: [Int], _ target: Int) -> [Int] {
var res = [-1, -1]
guard nums.count > 0 else {
return res
}
res[0] = _search(nums, target, true)
res[1] = _search(nums, target, false)
return res
}
private func _search(nums: [Int], _ target: Int, _ isLeft: Bool) -> Int {
var left = 0
var right = nums.count - 1
var mid = 0
while left + 1 < right {
mid = (right - left) / 2 + left
if nums[mid] == target {
if isLeft {
right = mid
} else {
left = mid
}
} else if nums[mid] > target {
right = mid - 1
} else {
left = mid + 1
}
}
if isLeft {
if _isIndexValid(left, nums, target) {
return left
}
if _isIndexValid(right, nums, target) {
return right
}
} else {
if _isIndexValid(right, nums, target) {
return right
}
if _isIndexValid(left, nums, target) {
return left
}
}
return -1
}
private func _isIndexValid(index: Int, _ nums: [Int], _ target: Int) -> Bool {
return index >= 0 && index < nums.count && nums[index] == target
}
}