【算法题】找终点

265次阅读
没有评论

共计 938 个字符,预计需要花费 3 分钟才能阅读完成。

给定一个正整数数组,设为nums,最大为100个成员,求从第一个成员开始,正好走到数组最后一个成员,所使用的最少步骤数。
要求:
1、第一步必须从第一元素开始,且1<=第一步的步长<len/2;(len为数组的长度,需要自行解析)。
2、从第二步开始,只能以所在成员的数字走相应的步数,不能多也不能少, 如果目标不可达返回-1,只输出最少的步骤数量。
3、只能向数组的尾部走,不能往回走。

  • 输入描述:
    由正整数组成的数组,以空格分隔,数组长度小于100,请自行解析数据数量。
  • 输出描述:
    正整数,表示最少的步数,如果不存在输出-1

示例1

输入
7 5 9 4 2 6 8 3 5 4 3 9
输出
2
说明
第一步: 第一个可选步长选择2,从第一个成员7开始走2步,到达9;第二步: 从9开始,经过自身数字9对应的9个成员到最后。

示例2

输入
1 2 3 7 1 5 9 3 2 1
输出
-1

import java.util.Scanner;

/**
 * @since 2022年4月21日
 */
public class GetFinal {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String line = scanner.nextLine();
        String[] strArr = line.split(" ");

        int stepSmallest = 0;
        for (int i = 1; i < strArr.length / 2; i++) {
            // 第一步走到索引 i
            int index = i;
            int step = 0;
            while (true) {
                if (index >= strArr.length) {
                    stepSmallest = -1;
                    break;
                }
                step++;
                int current = Integer.parseInt(strArr[index]);
                if (strArr.length - 1 == index) {
                    if (stepSmallest <= 0) {
                        stepSmallest = step;
                    } else if (stepSmallest <= step) {

                    } else {
                        stepSmallest = step;
                    }
                    break;
                }
                index += current;
            }
        }

        System.out.println(stepSmallest);
    }
}
正文完
 
裴先生
版权声明:本站原创文章,由 裴先生 2022-04-22发表,共计938字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
本站勉强运行: