华为OD机试算法:最大时间

给定一个包含6个整数的数组,任务是找到能表示的最大24小时制时间,输出有效时间或"invalid"。需先对数组排序,然后遍历所有可能的时间组合,确保小时、分钟和秒不超过其限制。
摘要由CSDN通过智能技术生成
题目描述

给定一个数组,里面有 6 个整数,求这个数组能够表示的最大 24 进制的时间是多少,输出这个时间,无法表示输出 invalid。

输入描述

输入为一个整数数组,数组内有六个整数。

输入整数数组长度为 6,不需要考虑其它长度,元素值为 0 或者正整数,6 个数字每个数字只能使用一次。

输出描述

输出为一个 24 进制格式的时间,或者字符串”invalid“。

用例

输入

[0,2,3,0,5,6]

输出

23:56:00

说明

题目解析

  • 1.

    首先,将输入的整数数组按照从小到大的顺序排序。

  • 2.

    然后,遍历所有可能的时间组合,对于每个时间组合,判断是否满足 24 进制时间的要求。具体来说,需要满足以下条件:

    • 小时部分的数字之和小于等于 23;

    • 分钟部分的数字之和小于等于 59;

    • 秒钟部分的数字之和小于等于 59。

  • 3.

    如果找到一个满足条件的时间组合,将其转换为 24 进制格式并输出。如果没有找到满足条件的时间组合,则输出 "invalid"。

JavaScript算法源码
 
const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on("line", (line) => {
  const arr = JSON.parse(line);

  const regExp = /(([01][0-9])|([2][0-3]))([0-5][0-9])([0-5][0-9])/;

  let dfs = (arr, used, path, res) => {
    if (path.length === arr.length) {
      if (regExp.test(path.join(""))) res.push([...path]);
      return;
    }

    for (let i = 0; i < arr.length; i++) {
      if (!used[i]) {
        path.push(arr[i]);
        used[i] = true;
        dfs(arr, used, path, res);
        used[i] = false;
        path.pop();
      }
    }
  };

  const res = [];
  dfs(arr, arr.slice().fill(false), [], res);

  if (!res.length) return console.log("invalid");

  const max = res.sort().at(-1);
  console.log(`${max[0]}${max[1]}:${max[2]}${max[3]}:${max[4]}${max[5]}`);
});

Java算法源码
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.Collections;

public class Main {
    private static final Pattern c = Pattern.compile("(([01][0-9])|([2][0-3])):([0-5][0-9]):([0-5][0-9])");

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        Integer[] arr = Arrays.stream(s.substring(1, s.length() - 1).split(","))
                .map(Integer::parseInt)
                .toArray(Integer[]::new);

        System.out.println(getResult(arr));
    }

    public static String getResult(Integer[] arr) {
        ArrayList<String> res = new ArrayList<>();
        dfs(arr, new boolean[arr.length], new LinkedList<>(), res);

        if (res.isEmpty()) return "invalid";
        Collections.sort(res, Collections.reverseOrder());
        return res.get(0);
    }

    public static void dfs(Integer[] arr, boolean[] used, LinkedList<Integer> path, ArrayList<String> res) {
        int pathLength = path.size();
        if (pathLength == arr.length) {
            Integer[] t = path.toArray(new Integer[0]);
            String time = t[0] + "" + t[1] + ":" + t[2] + "" + t[3] + ":" + t[4] + "" + t[5];

            if (c.matcher(time).matches()) res.add(time);
            return;
        }

        for (int i = 0; i < arr.length; i++) {
            if (!used[i]) {
                path.add(arr[i]);
                used[i] = true;
                dfs(arr, used, path, res);
                used[i] = false;
                path.removeLast();
            }
        }
    }
}
Python算法源码
import re

arr = [...]  # 请将这里的省略号替换为实际的数组内容

p = re.compile("(([01][0-9])|([2][0-3]))([0-5][0-9])([0-5][0-9])")

def dfs(arr, used, path, res):
    if len(path) == len(arr):
        tmp = "".join(map(str, path))
        if p.match(tmp):
            res.append(path[:])
        return

    for i in range(len(arr)):
        if not used[i]:
            path.append(arr[i])
            used[i] = True
            dfs(arr, used, path, res)
            used[i] = False
            path.pop()

def getResult():
    res = []
    dfs(arr, [False] * (len(arr)), [], res)

    if len(res) == 0:
        return "invalid"

    t = max(res)

    return f"{t[0]}{t[1]}:{t[2]}{t[3]}:{t[4]}{t[5]}"

print(getResult())

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一剑破天门

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值