华为OD 跳房子

题目描述

跳房子,也叫跳飞机,是一种世界性的儿童游戏。

游戏参与者需要分多个回合按顺序跳到第1格直到房子的最后一格。

跳房子的过程中,可以向前跳,也可以向后跳。

假设房子的总格数是count,小红每回合可能连续跳的步教都放在数组steps中,请问数组中是否有一种步数的组合,可以让小红两个回合跳到量后一格?

如果有,请输出索引和最小的步数组合。

注意:

  • 数组中的步数可以重复,但数组中的元素不能重复使用。
  • 提供的数据保证存在满足题目要求的组合,且索引和最小的步数组合是唯一的。

输入描述

第一行输入为房子总格数count,它是int整数类型。 第二行输入为每回合可能连续跳的步数,它是int整数数组类型。

输出描述

返回索引和最小的满足要求的步数组合(顺序保持steps中原有顺序)

备注

  • count ≤ 1000
  • 0 ≤ steps.length ≤ 5000
  • -100000000 ≤ steps ≤ 100000000

用例1

输入

[1,4,5,2,2]
7

输出

[5, 2]

用例2

输入

[-1,2,4,9,6]
8

输出

[-1, 9]

说明

此样例有多种组合满足两回合跳到最后,譬如:[-1,9],[2,6],其中[-1,9]的索引和为0+3=3,[2,6]的索和为1+4=5,所以索引和最小的步数组合[-1,9]

import java.util.Scanner;
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        int[] steps = Arrays.stream(str.substring(1,
                                    str.length() - 1).split(",")).mapToInt(Integer::parseInt).toArray();
        int total = Integer.valueOf(in.nextLine());
        int minIndex = Integer.MAX_VALUE;

        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < steps.length; i++) {
            if (map.get(steps[i]) == null) {
                map.put(steps[i], i);
            }
        }
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < steps.length; i++) {
            if (map.get(total - steps[i]) != null) {
                if (i + map.get(total - steps[i]) < minIndex) {
                    minIndex = i + map.get(total - steps[i]);
                    list.clear();
                    list.add(steps[i]);
                    list.add(total - steps[i]);
                }
            }
        }
        StringBuilder builder = new StringBuilder();
        builder.append("[").append(list.get(0)).append(",").append(list.get(
                    1)).append("]");
        System.out.println(builder.toString());
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值