Categorías
Algorithms

LeetCode – Próxima hora más cercana (Java)

Dado un tiempo representado en el formato «HH: MM», forme el siguiente tiempo más cercano reutilizando los dígitos actuales. No hay límite en la cantidad de veces que se puede reutilizar un dígito.

Puede asumir que la cadena de entrada proporcionada es siempre válida. Por ejemplo, «01:34», «12:09» son todos válidos. «1:34», «12: 9» no son válidos.

Ejemplo 1:

Entrada: «19:34»
Salida: «19:39»
Explicación: La siguiente hora más cercana a elegir entre los dígitos 1, 9, 3, 4 es 19:39, que ocurre 5 minutos más tarde. No son las 19:33, porque esto ocurre 23 horas y 59 minutos después.

Solución Java

public String nextClosestTime(String time) {
    ArrayList<Integer> list = new ArrayList<>();
    ArrayList<Character> charList = new ArrayList<>();
    TreeSet<Integer> set = new TreeSet<>();
 
    //get digit list
    for (int i = 0; i < time.length(); i++) {
        if (time.charAt(i) >= '0' && time.charAt(i) <= '9') {
            charList.add(time.charAt(i));
        }
    }
 
    //get all possible number combinations
    for (int i = 0; i < charList.size(); i++) {
        for (int j = 0; j < charList.size(); j++) {
            set.add(Integer.parseInt(charList.get(i) + "" + charList.get(j)));
        }
    }
 
    //add to list
    list.addAll(set);
 
    String[] arr = time.split(":");
    int hour = Integer.parseInt(arr[0]);
    int min = Integer.parseInt(arr[1]);
 
    int idxMin = search(list, min);
    int idxHour = search(list, hour);
 
    String hh = "";
    String mm = "";
 
    if (idxMin < list.size() - 1 && list.get(idxMin + 1) < 60) {
        hh = hour + "";
        mm = list.get(idxMin + 1) + "";
    } else {
        if (idxHour < list.size() - 1 && list.get(idxHour + 1) < 24) {
            hh = list.get(idxHour + 1) + "";
            mm = list.get(0) + "";
        } else {
            hh = list.get(0) + "";
            mm = list.get(0) + "";
        }
    }
 
    if (hh.length() < 2) {
        hh = "0" + hh;
    }
 
    if (mm.length() < 2) {
        mm = "0" + mm;
    }
 
    return hh + ":" + mm;
}
 
private int search(ArrayList<Integer> list, int target) {
    int i = 0;
    int j = list.size() - 1;
 
    while (i < j) {
        int m = i + (j - i) / 2;
        if (list.get(m) < target) {
            i = m + 1;
        } else {
            j = m;
        }
    }
 
    return j;
}

Por Programación.Click

Más de 20 años programando en diferentes lenguajes de programación. Apasionado del code clean y el terminar lo que se empieza. ¿Programamos de verdad?

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *