题目链接 HORSE-RACING DUALS
思路:
- 创建数组 array 并读取 Pi 值存储于其中
- 更改 IFS 为换行符(’\n’)后, 使用 sort -n 对 array 进行排序, 结果存储到新的数组 sorted_array
- 遍历 sorted_array, 依次比较"后一元素值与当前元素值的差值"的大小:
- 定义最小值 minimum 为 sorted_array 最后一个元素与第一个元素的差值
- 定义当前值 current 为 sorted_array 第一个元素的值
- 从第二个元素开始循环遍历 sorted_array, 临时差值 difference 为 当前元素与上一个元素的差值, minimum 取 difference 和 minimum之中的较小值, 替换 current 为 difference, 继续循环
知识点:
- declare -a array : 定义数组
- IFS=$’\n’ : 将 IFS 更改为 换行符
- sort -n : 根据字符串数值升序排序
- <<< : 将后面的内容作为前面命令的标准输入
- ${sorted_array[@]:1} : 从第二个元素开始截取数组
Bash 代码如下:
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
read -r N
declare -a array
for (( i=0; i<$N; i++ )); do
read -r Pi
array[i]=${Pi}
done
IFS=$'\n'
sorted_array=($(sort -n <<<"${array[*]}"))
# Write an action using echo
# To debug: echo "Debug messages..." >&2
minimum=$((${sorted_array[N-1]} - ${sorted_array[0]}))
current=${sorted_array[0]}
for next in "${sorted_array[@]:1}"; do
difference=$((${next} - ${current}))
if [ ${difference} -lt ${minimum} ]; then
minimum=${difference}
fi
if [ ${minimum} -eq 0 ];then
break
fi
current=${next}
done
echo ${minimum}