forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SearchInRotatedSortedArrayII.swift
39 lines (34 loc) · 1.12 KB
/
SearchInRotatedSortedArrayII.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
/**
* Question Link: https://leetcode.com/problems/search-in-rotated-sorted-array-ii/
* Primary idea: Binary Search, check left or right is sorted, then search in the part, jump if dupliates
*
* Time Complexity: O(logn), Space Complexity: O(1)
*/
class SearchInRotatedSortedArrayII {
func search(nums: [Int], _ target: Int) -> Bool {
var left = 0
var right = nums.count - 1
while left <= right {
var mid = (right - left) / 2 + left
if nums[mid] == target {
return true
}
if nums[mid] > nums[left] {
if nums[mid] > target && target >= nums[left] {
right = mid - 1
} else {
left = mid + 1
}
} else if nums[mid] < nums[left]{
if nums[mid] < target && target <= nums[right] {
left = mid + 1
} else {
right = mid - 1
}
} else {
left += 1
}
}
return false
}
}