Skip to content

Commit a2b3662

Browse files
committed
2.3-7
1 parent 948208a commit a2b3662

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

exercises/2.3-7.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package exercises
2+
3+
import (
4+
"arithmetic/sort"
5+
)
6+
7+
func SearchSum(arr []int, sum int) bool {
8+
sort.MergeSort(arr, 0, len(arr)-1) //归并排序 O(n lgn) 复杂度
9+
if arr[0] > sum {
10+
return false
11+
}
12+
for i := 0; i < len(arr)-1; i++ { //n次循环 加二分查找 也是 O(n lgn) 复杂度
13+
ret := binarySearch(arr[i+1:], sum-arr[i])
14+
if ret != -1 {
15+
return true
16+
}
17+
}
18+
return false
19+
}
20+
func binarySearch(arr []int, key int) int {
21+
start, end := 0, len(arr)-1
22+
for start <= end {
23+
mid := start + (end-start)/2
24+
if key > arr[mid] {
25+
start = mid + 1
26+
} else if key < arr[mid] {
27+
end = mid - 1
28+
} else {
29+
return mid
30+
}
31+
}
32+
return -1
33+
}

exercises/2.3-7_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package exercises
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestSearchSum(t *testing.T) {
8+
arr := []int{5, 7, 3, 2, 7, 55, 33, 55, 13, 56, 758}
9+
if !SearchSum(arr, 8) {
10+
t.Fail()
11+
}
12+
}

sort/insert_sort.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ func InsertSort2(arr []int) {
3232

3333
}
3434

35+
//二分查找递归版
3536
func suitableIndex(list []int, start int, end int, current int) int {
3637
// 比到最后没的比的时候就去对比下当前位置与待排元素的大小,并返回较大值的位置
3738
if start >= end {
@@ -52,6 +53,8 @@ func suitableIndex(list []int, start int, end int, current int) int {
5253
}
5354

5455
}
56+
57+
//二分查找循环版
5558
func suitableIndex2(list []int) int {
5659
key := len(list) - 1
5760
start, end := 0, len(list)-2

0 commit comments

Comments
 (0)