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.
1
Example 1:
2
3
Input: [1,2,3,4]
4
Output: "23:41"
5
Example 2:
6
7
Input: [5,5,5,5]
8
Output: ""
9
10
11
Note:
12
13
A.length == 4
14
0 <= A[i] <= 9
Copied!
暴力解法,列出四个数字的全排列,然后比较有效的最大值。
1
class Solution {
2
3
public:
4
string largestTimeFromDigits(vector<int>& A) {
5
int res = -1;
6
for (int i = 0; i < 4; i++)
7
for (int j = 0; j < 4; j++)if (j != i)
8
for (int k = 0; k < 4; k++)if (k != i && k != j) {
9
int l = 6 - i - j - k;
10
int hours = 10 * A[i] + A[j];
11
int mins = 10 * A[k] + A[l];
12
if (hours < 24 && mins < 60)
13
res = max(res, hours * 60 + mins);
14
}
15
if (res >= 0) {
16
char c[6];
17
sprintf(c, "%.2d:%.2d", res / 60, res % 60);
18
return c;
19
}
20
return "";
21
}
22
};
Copied!
执行用时 :4 ms, 在所有 C++ 提交中击败了75.93%的用户 内存消耗 :8.1 MB, 在所有 C++ 提交中击败了97.78%的用户
Copy link