dongyuchen0214 2017-07-26 08:52
浏览 21
已采纳

接受意见的最佳做法

I have written a mergeSort function, which sorted 1 million integers in 750ms, but it takes 9 seconds to take input.

This is how I have taken input to my slice, which is to be sorted.

code snippet:

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

What I need is, an efficient way to take integers as input into a slice. Input contains only integers, seperated by space or each integer in new-line.

Sample Input 1:

3
9
1
13

Sample Input 2:

3 9 1 13

If efficient solution is available for any one type of Input, it would suffice

  • 写回答

2条回答 默认 最新

  • doushenjia8514 2018-04-17 16:48
    关注
    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 '
    ', 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, '
    ')
        // 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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加