Tuesday, August 4, 2020

LeetCode [949] Largest Time for Given Digits

949. Largest Time for Given Digits
Easy

Given an array of 4 digits, return the largest 24 hour time that can be made.

The smallest 24 hour time is 00:00, and the largest is 23:59.  Starting from 00:00, a time is larger if more time has elapsed since midnight.

Return the answer as a string of length 5.  If no valid time can be made, return an empty string.

 

Example 1:

Input: [1,2,3,4]
Output: "23:41"

Example 2:

Input: [5,5,5,5]
Output: ""

 

Note:

  1. A.length == 4
  2. 0 <= A[i] <= 9
class Solution {
    public String largestTimeFromDigits(int[] A) {
        Integer[] AI = Arrays.stream(A).boxed().toArray( Integer[]::new );
        Arrays.sort(AI, Collections.reverseOrder());
        int hour=0, minute=0;

        StringBuilder sb = new StringBuilder();
        for(int i=0; i<4; ++i){
            for(int j=0; j<4; ++j){
                if(j==i) continue;
                hour = AI[i]*10+AI[j];
                if(hour<24){
                    for(int k=0; k<4; k++){
                        if(k==i || k==j) continue;
                        for(int t=0; t<4; t++){
                            if(t==i||t==j||t==k) continue;
                            minute = AI[k]*10+AI[t];
                            if(minute<60){
                                sb.append(hour/10);
                                sb.append(hour%10);
                                sb.append(":");
                                sb.append(minute/10);
                                sb.append(minute%10);
                                return sb.toString();
                            }
                        }
                    }
                }
            }
        }
        return "";
    }
}

No comments:

Post a Comment