/*
* 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)
}
}
}