反转int切片的两种写法

方法1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

import "fmt"

func main() {

ints := []int{1, 2, 3, 4, 5}
ret := make([]int, len(ints))
for i := len(ints) - 1; i >= 0; i-- {
ret[len(ints)-i-1] = ints[i]
}
fmt.Println(ret)

}

方法2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

import "fmt"

func main() {

ints := []int{1, 2, 3, 4, 5}

for i, j := 0, len(ints)-1; i < j; i, j = i+1, j-1 {
ints[i], ints[j] = ints[j], ints[i]
}
fmt.Println(ints)

}

统计切片中 两个数之和=给定值的组合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import "fmt"

func main() {
var arr = []int{4, 18, 22, 14, 20, 25, 42, 60, 12, 40, 36, 0, 15}

hash := make(map[int]int) //key 存具体数字, value存索引
ret := [][2]int{}

sum := 40
for i := 0; i < len(arr); i++ {
if _, ok := hash[sum-arr[i]]; ok {
ret = append(ret, [2]int{hash[sum-arr[i]], i})
} else {
hash[arr[i]] = i
}
}

for _, item := range ret {
fmt.Printf("%d+%d=40\n", arr[item[0]], arr[item[1]])
}

}