• 上机编程认证01


    /*
    * Copyright (c) Huawei Technologies Co., Ltd. 2019-2021. All rights reserved.
    * Description: 上机编程认证
    * Note: 缺省代码仅供参考,可自行决定使用、修改或删除
    * 只能import Go标准库
    */
    package main

    import (
    "bufio"
    "fmt"
    "io"
    "math"
    "os"
    "sort"
    "strconv"
    "strings"
    )

    // 待实现函数,在此函数中填入答题代码
    func getMedian(numbers []int) int {
    if len(numbers) < 0 {
    return 0
    }
    preFloatNum := float64(len(numbers)) / 3
    preMediaNum := int(math.Ceil(preFloatNum))
    sort.Ints(numbers)
    floatNum := float64(preMediaNum) / 2
    mediaNum := int(math.Ceil(floatNum))
    halfNum := preMediaNum - mediaNum
    if halfNum > 0 && mediaNum > 0 && mediaNum == halfNum && (mediaNum-1) >= 0 {
    totalNum := numbers[mediaNum-1] + numbers[mediaNum]
    totalFloatNum := float64(totalNum) / 2
    return int(math.Ceil(totalFloatNum))
    }
    return numbers[halfNum]
    }

    func main() {
    reader := bufio.NewReader(os.Stdin)
    numbers := readInputIntArray(reader)
    result := getMedian(numbers)
    fmt.Println(result)
    }

    func readInputIntArray(reader *bufio.Reader) []int {
    var num int
    if _, err := fmt.Fscanf(reader, "%d\n", &num); err != nil {
    fmt.Println(err.Error())
    return nil
    }
    if num == 0{
    return []int{}
    }
    lineBuf, err := reader.ReadString('\n')
    if err != nil && err != io.EOF {
    fmt.Println(err.Error())
    return nil
    }
    lineBuf = strings.TrimRight(lineBuf, "\r\n")
    lineBuf = strings.TrimSpace(lineBuf)
    intNums := map2IntArray(lineBuf, " ")
    if len(intNums) != num{
    fmt.Println("int string len is error")
    return nil
    }
    return intNums
    }

    func map2IntArray(str string, dem string) []int {
    tempArray := strings.Split(str, dem)
    result := make([]int, len(tempArray))
    for index, value := range tempArray {
    value = strings.TrimSpace(value)
    intVal, err := strconv.Atoi(value)
    if err == nil {
    result[index] = intVal
    }
    }
    return result
    }



    //test


    package main

    import (
    "testing"
    )

    func TestEncodingVerify(t *testing.T) {
    tests := []struct{
    list []int
    want int
    }{
    {list: []int{122,123,11,12,12,11,22,11,22,1},want:11},
    {list: []int{111,22,11,22,1},want:6},
    }
    for _,tt := range tests{
    if got := getMedian(tt.list);got != tt.want {
    t.Errorf("getMedian(%v) got %d is not the expected value %d",
    tt.list,got, tt.want)
    }
    }
    }


  • 相关阅读:
    Linux PCI网卡驱动的详细分析
    moand的编程学形式:一个(高阶)类型包办程序的组织--类型关乎复合
    范畴论完全解读:函子是范畴(高阶类型)间的映射
    函数式编程从起点到终点
    锁的本质:操作的序列化
    并发编程概述--C#并发编程经典实例
    异步IO的概念
    基于事件的并发编程
    runloop是iOS系统上的actor模式
    Monad、Actor与并发编程--基于线程与基于事件的并发编程之争
  • 原文地址:https://www.cnblogs.com/gongxianjin/p/16123203.html
Copyright © 2020-2023  润新知