949. Largest Time for Given Digits

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(vector<int>& A) {
string res;
sort(A.begin(), A.end());
do {
string hour = {char(A[0] + '0'), char(A[1] + '0')}, minute = {char(A[2] + '0'), char(A[3] + '0')};
res = (hour <= "23" && minute <= "59") ? (hour + ":" + minute) : res;
} while(next_permutation(A.begin(), A.end()));
return res;
}
};
``````

``````class Solution {
public:
string largestTimeFromDigits(vector<int>& A) {
string res;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
for (int k = 0; k < 4; ++k) {
if (i == j || i == k || j == k) continue;
string hour = {char(A[i] + '0'), char(A[j] + '0')}, minute = {char(A[k] + '0'), char(A[6 - i - j - k] + '0')}, t = hour + ":" + minute;
if (hour <= "23" && minute <= "59" && res < t) res = t;
}
}
}
return res;
}
};
``````

``````class Solution {
public:
string largestTimeFromDigits(vector<int>& A) {
for (int h = 23; h >= 0; --h) {
for (int m = 59; m >= 0; --m) {
vector<int> cnt(10);
bool valid = true;
++cnt[h < 10 ? 0 : h / 10];
++cnt[h < 10 ? h : h % 10];
++cnt[m < 10 ? 0 : m / 10];
++cnt[m < 10 ? m : m % 10];
for (int num : A) {
if (--cnt[num] < 0) {
valid = false;
break;
}
}
string hour = to_string(h), minute = to_string(m);
if (valid) return (h < 10 ? "0" + hour : hour) + ":" + (m < 10 ? "0" + minute : minute);
}
}
return "";
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/949

https://leetcode.com/problems/largest-time-for-given-digits/submissions/

https://leetcode.com/problems/largest-time-for-given-digits/discuss/207126/Elegant-C%2B%2B-solution!)

https://leetcode.com/problems/largest-time-for-given-digits/discuss/202234/Java-Super-Short-Solution-!!!

https://leetcode.com/problems/largest-time-for-given-digits/discuss/200693/JavaPython-3-11-liner-O(64)-w-comment-6-ms.

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation