forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchInsertPosition.swift
More file actions
38 lines (33 loc) · 913 Bytes
/
SearchInsertPosition.swift
File metadata and controls
38 lines (33 loc) · 913 Bytes
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
/**
* Question Link: https://leetcode.com/problems/search-insert-position/
* Primary idea: Binary Search, until two variables left
*
* Time Complexity: O(logn), Space Complexity: O(1)
*/
class SearchInsertPosition {
func searchInsert(nums: [Int], _ target: Int) -> Int {
guard nums.count > 0 else {
return 0
}
var left = 0
var right = nums.count - 1
var mid = 0
while left + 1 < right {
mid = (right - left) / 2 + left
if nums[mid] == target {
return mid
} else if nums[mid] < target {
left = mid
} else {
right = mid
}
}
if nums[right] < target {
return right + 1
}
if nums[left] >= target {
return left
}
return right
}
}