题目一:【跳跃游戏II】力扣——45
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
示例:
输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
说明:
假设你总是可以到达数组的最后一个位置。
#!/bin/bash
#跳跃游戏II
#author:yzt 2019-11-19
#
read -t 40 -p "请输入一个非负整数数组:" contents
echo "$contents" | sed 's#\[\|\]##g'|sed 's#,#\n#g'|grep -n -v "^$" >tmp.txt
cat tmp.txt | head -n1 >tmp1.txt
totle1=`cat tmp.txt|wc -l`
declare ik=0
export ii=$ik
export totle=$totle1
tiaoyuediedai(){
ii=$[$ii+1]
cat /dev/null >tmp2.txt
for i in `cat $1`
do
first=`echo "$i"|awk -F : '{print $1}'`
second=`echo "$i"|awk -F : '{print $2}'`
for((j=1;j<="$second";j++))
do
hangshu=$[$first+$j]
sed -n "$hangshu p" tmp.txt >>tmp2.txt
done
done
cat tmp2.txt|sort -n |uniq >tmp1.txt
test_cont=`cat tmp1.txt|awk -F : -v k=$totle '$1>=k {print $0}'`
cat tmp1.txt|awk -F : '$2>0 {print $0}' >file1.txt
if [ ! -z $test_cont ];then
echo "$ii"
exit 0
else
if [ -s file1.txt ];then
tiaoyuediedai "tmp1.txt"
else
echo "此数组不能到达最后一个位置"
fi
fi
}
tiaoyuediedai "tmp1.txt"
脚本逻辑:
第一:记录每个位置及其上面的数值,并将数组元素以一行一个的方式存储在文档1中
第二:使用递归的思想,比如数组的第一位是3,那么记录为:1:3;对3进行遍历,且用位置数1加上遍历数,分别得到:2、3、4;进而获取原文档1第2行、第3行、第4行的项,将这些项导入到另一文档2中,再进行遍历
第三:当文档2中的项的位置数出现大于或等于原数组个数时,终止迭代并返回循环次数
第四:有一种情况会使得数组不能达到最后一个位置,这一点需要考虑
脚本效果:
[root@localhost leetcode]# ./tiaoyueyouxiII.sh
请输入一个非负整数数组:[2,3,1,1,4]
2
[root@localhost leetcode]# ./tiaoyueyouxiII.sh
请输入一个非负整数数组:3,2,1,0,4]
此数组不能到达最后一个位置
[root@localhost leetcode]# ./tiaoyueyouxiII.sh
请输入一个非负整数数组:[2,3,1,4,5,1,0,1]
3