6ms Java solution


  • 0
    T

    This is O(4 * 4 * 4 * 4) solution, much faster than O(24 * 60) solutions:

    public String nextClosestTime1(String time) {
        int[] digits = new int[]{time.charAt(0) - '0', time.charAt(1) - '0', time.charAt(3) - '0', time.charAt(4) - '0'};
        int t = Integer.parseInt(time.substring(0, 2)) * 60 + Integer.parseInt(time.substring(3, 5));
        int min = 100000, minH = 0, minM = 0;
        for (int i = 0; i < 4; i++) {
            if (digits[i] > 2) continue;
            for (int j = 0; j < 4; j++) {
                int h = digits[i] * 10 + digits[j];
                if (h >= 24) continue;
                for (int q = 0; q < 4; q++) {
                    if (digits[q] >= 6) continue;
                    for (int p = 0; p < 4; p++) {
                        int m = digits[q] * 10 + digits[p];
                        int diff = h * 60 + m - t;
                        if (diff <= 0) diff += 24 * 60;
                        if (diff < min) {
                            min = diff;
                            minH = h;
                            minM = m;
                        }
                    }
                }
            }
        }
        return (minH < 10 ? "0" + minH : "" + minH) + ":" + (minM < 10 ? "0" + minM : "" + minM);
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.