-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathanswer.go
More file actions
38 lines (34 loc) · 758 Bytes
/
answer.go
File metadata and controls
38 lines (34 loc) · 758 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
// O(log(n))
func searchInsert(nums []int, target int) int {
hi := len(nums)-1
lo := 0
mid := hi/2
if target > nums[hi] {
return hi+1
}
for lo <= hi {
if nums[mid] == target{
return mid
}else if nums[mid] < target{
lo = mid+1
}else{
hi = mid-1
}
mid = (hi-lo) + lo
}
return lo
}
// O(n)
func searchInsert(nums []int, target int) int {
// If target is greater than any value
if target > nums[len(nums)-1] {
return len(nums)
}
// Loop through array and compare values to target
for i := 0; i < len(nums); i++{
if nums[i] >= target {
return i
}
}
return 0
}