那么问题来了,我用bfio就是不行,indexoutofbound
package main
import (
"fmt"
"sort"
)
func main() {
var (
l, tar int
)
fmt.Scanln(&l,&tar)
//读取第二行
temp := 0
//sc.Scan()
//line2 := strings.Split(sc.Text(), " ")
arr := make([]int, l)
for i := range arr {
fmt.Scan(&temp)
arr[i] = temp
}
res := twoSumTarget(arr, tar)
for _, r := range res {
fmt.Printf("%d %d\n", r[0], r[1])
}
// sc := bufio.NewScanner(os.Stdin)
// // 读取第一行获取l和tar
// bs := make([]byte, 2000*64)
// sc.Buffer(bs, len(bs))
// sc.Scan()
// line1 := strings.Split(sc.Text(), " ")
// l, _ = strconv.Atoi(line1[0])
// tar, _ = strconv.Atoi(line1[0])
//读取第二
//sc.Scan()
//line2 := strings.Split(sc.Text(), " ")
}
func twoSumTarget(nums []int, target int) [][]int {
sort.Ints(nums)
lo := 0
hi := len(nums) - 1
res := [][]int{}
for lo < hi {
sum := nums[lo] + nums[hi]
left := nums[lo]
right := nums[hi]
if sum < target {
for lo < hi && nums[lo] == left {
lo++
}
} else if sum > target {
for lo < hi && nums[hi] == right {
hi--
}
} else { //相等的情况
res = append(res, []int{left, right}) //先加入结果
for lo < hi && nums[lo] == left {
lo++
}
for lo < hi && nums[hi] == right {
hi--
}
}
}
return res
}