-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch-insert-position.go
More file actions
55 lines (48 loc) · 1.12 KB
/
Copy pathsearch-insert-position.go
File metadata and controls
55 lines (48 loc) · 1.12 KB
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
package main
import (
"fmt"
)
func searchInsert(nums []int, target int) int {
// Taking care of some edge cases
// No need to process much in these cases
if len(nums) == 0 || target < nums[0] {
return 0
} else if target > nums[len(nums)-1] {
return len(nums)
}
// Binary search
start, end := 0, len(nums)-1
for {
i := (start + end) / 2
// println(start, i, end)
if nums[i] == target || i == start || i == end {
if nums[i] < target {
return i + 1
}
return i
}
if nums[i] < target {
start = i
} else {
end = i
}
}
}
func main() {
test := []int{12, 14, 15, 16, 17, 19}
fmt.Printf("Testing: %v\n", test)
result := searchInsert(test, 11)
fmt.Printf("Yields : %v\n", result)
fmt.Printf("Testing: %v\n", test)
result = searchInsert(test, 12)
fmt.Printf("Yields : %v\n", result)
fmt.Printf("Testing: %v\n", test)
result = searchInsert(test, 13)
fmt.Printf("Yields : %v\n", result)
fmt.Printf("Testing: %v\n", test)
result = searchInsert(test, 18)
fmt.Printf("Yields : %v\n", result)
fmt.Printf("Testing: %v\n", test)
result = searchInsert(test, 20)
fmt.Printf("Yields : %v\n", result)
}