【问题标题】:Best practices to take input接受输入的最佳实践
【发布时间】:2017-07-26 08:52:16
【问题描述】:

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

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

代码sn-p:

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

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

【问题讨论】:

  • 您需要输入什么?它是以 10 为基数的字符串表示形式的一系列整数吗?他们只是签名还是未签名?如果您可以发布一个有用的示例。
  • 以 10 为底的正整数

标签: arrays go io stdout stdin


【解决方案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 符文并简单地在 ' ' 上拆分的自定义拆分函数来进一步优化。

【讨论】:

    【解决方案2】:
    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
    }
    

    【讨论】:

      猜你喜欢
      • 2011-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      • 2013-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多