采纳意见的最佳做法
Best practices to take input
我写了一个 mergeSort
函数,它在 750 毫秒内对 100 万个整数进行排序,但需要 9 秒来获取输入。
这就是我将输入输入到要排序的切片中的方式。
代码片段:
array := make([]int,n)
for i := 0; i < n; i++ {
fmt.Scanf("%d",&array[i])
}
我需要的是一种将整数作为切片输入的有效方法。
输入仅包含整数,由 space 或换行符中的每个整数分隔。
示例输入 1:
3
9
1
13
示例输入 2:
3 9 1 13
如果对任何一种类型的输入都有有效的解决方案,那就足够了
假设您的输入是 space 个分隔的有符号整数(以 10 为基数),请尝试以下操作:
s := bufio.NewScanner(os.StdIn)
s.Split(bufio.ScanWords)
i := 0
for s.Scan() && i < n {
dest[i], _ = strconv.ParseInt(s.Text(), 10, 64)
i++
}
这表明使用快速基准测试比使用 fmt.Scanf
快大约 5 倍。它可能可以通过编写一个自定义拆分函数来进一步优化,该函数不必担心解析 UTF-8 符文,只需在 ' '
.
上拆分
package main
import (
"io/ioutil"
"os"
)
// inp is a variable in which we store our whole input
var inp []byte
// loc is used as index and remember till where we have seen our input
var loc int
func main() {
// we read whole input and store it in inp and then append '\n', so
// that we don't get any type index out of bound error, while
// scanning the last digit.
inp, _ = ioutil.ReadAll(os.Stdin)
inp = append(inp, '\n')
// when ever scanInt is called, it will return single value of type int
// usage:
// n := scanInt()
}
func scanInt() (res int) {
// skip if byte value doesn't belong to integer and break when it is
// an integer
for ; inp[loc] < 48 || inp[loc] > 57; loc++ {
}
// If it is an integer parse it completely else break return the result
for ; inp[loc] > 47 && inp[loc] < 58 ; loc++ {
res = (res << 1 ) + (res << 3) + int(inp[loc]-48)
}
return
}
我写了一个 mergeSort
函数,它在 750 毫秒内对 100 万个整数进行排序,但需要 9 秒来获取输入。
这就是我将输入输入到要排序的切片中的方式。
代码片段:
array := make([]int,n)
for i := 0; i < n; i++ {
fmt.Scanf("%d",&array[i])
}
我需要的是一种将整数作为切片输入的有效方法。 输入仅包含整数,由 space 或换行符中的每个整数分隔。
示例输入 1:
3
9
1
13
示例输入 2:
3 9 1 13
如果对任何一种类型的输入都有有效的解决方案,那就足够了
假设您的输入是 space 个分隔的有符号整数(以 10 为基数),请尝试以下操作:
s := bufio.NewScanner(os.StdIn)
s.Split(bufio.ScanWords)
i := 0
for s.Scan() && i < n {
dest[i], _ = strconv.ParseInt(s.Text(), 10, 64)
i++
}
这表明使用快速基准测试比使用 fmt.Scanf
快大约 5 倍。它可能可以通过编写一个自定义拆分函数来进一步优化,该函数不必担心解析 UTF-8 符文,只需在 ' '
.
package main
import (
"io/ioutil"
"os"
)
// inp is a variable in which we store our whole input
var inp []byte
// loc is used as index and remember till where we have seen our input
var loc int
func main() {
// we read whole input and store it in inp and then append '\n', so
// that we don't get any type index out of bound error, while
// scanning the last digit.
inp, _ = ioutil.ReadAll(os.Stdin)
inp = append(inp, '\n')
// when ever scanInt is called, it will return single value of type int
// usage:
// n := scanInt()
}
func scanInt() (res int) {
// skip if byte value doesn't belong to integer and break when it is
// an integer
for ; inp[loc] < 48 || inp[loc] > 57; loc++ {
}
// If it is an integer parse it completely else break return the result
for ; inp[loc] > 47 && inp[loc] < 58 ; loc++ {
res = (res << 1 ) + (res << 3) + int(inp[loc]-48)
}
return
}