-
Notifications
You must be signed in to change notification settings - Fork 15
/
AprilSolDay19.swift
51 lines (46 loc) · 1.68 KB
/
AprilSolDay19.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
//
// AprilSolDay19.swift
// LeetCodeChallenge
//
// Created by Michael Ho on 4/21/20.
// Copyright © 2020 Michael Ho. All rights reserved.
//
// LeetCode: https://leetcode.com/problems/search-in-rotated-sorted-array/
// The solution's runtime complexity must be in the order of O(log n).
class AprilSolDay19 {
func search(_ nums: [Int], _ target: Int) -> Int {
guard nums.count > 0 else { return -1 }
var start = 0
var end = nums.count - 1
while start <= end {
let mid = start + (end - start) / 2
let midVal = nums[mid]
if target == midVal {
return mid
} else if target == nums[start] {
return start
} else if target == nums[end] {
return end
} else if midVal > nums[start] {
// If it falls into this condition, it means the first half of
// the array is not rotated. Therefore, we can decide if the
// target falls into the first half or not.
if target < midVal, target > nums[start] {
end = mid - 1
} else {
start = mid + 1
}
} else {
// If it falls into this condition, it means the second half of
// the array is not rotated. Therefore, we can decide if the
// target falls into the second half or not.
if target > midVal, target < nums[end] {
start = mid + 1
} else {
end = mid - 1
}
}
}
return -1
}
}