采取投入的最佳做法

时间:2017-07-26 08:52:17

标签: arrays go io stdout stdin

我编写了一个mergeSort函数,它在750毫秒内对100万个整数进行了排序,但需要9秒才能输入。

这就是我将切片输入到切片的方式。

代码段:

array := make([]int,n)
for i := 0; i < n; i++ {
    fmt.Scanf("%d",&array[i])
}

我需要的是一种将整数作为输入到切片中的有效方法。 输入仅包含整数,按空格分隔或新行中的每个整数。

示例输入1:

3
9
1
13

示例输入2:

3 9 1 13

如果有效的解决方案适用于任何一种类型的输入,那就足够了

2 个答案:

答案 0 :(得分:1)

假设您的输入是空格分隔的有符号整数(在基数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符文而只是拆分为' '

答案 1 :(得分:0)

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
}
相关问题