我试图从给定的 4 位数字中找到最大有效时间。我使用了数字(2,4,0,0)。代码返回 20:42,而它应该返回 20:40。 关于如何解决这个问题有什么建议吗?
import java.util.ArrayList;
import java.util.List;
public class MaxTimeCombination {
public static void main(String[] args) {
System.out.println(solution(2, 4, 0, 0));
System.out.println(solution(3, 0, 7, 0));
}
public static String solution(int A, int B, int C, int D) {
// brute force permutation
int[] temp = new int[] {A, B, C, D};
List<List<Integer>> permutation = permute(temp);
int h = Integer.MIN_VALUE;
int m = Integer.MIN_VALUE;
boolean exists = false;
/* System.out.println("Permutations:" + permutation);
for (int i = 0; i < permutation.size(); i++) {
if (permutation.get(i).get(0) > 0 && permutation.get(i).get(0) < 3 ){
List <Integer> output = permutation.get(i);
System.out.println(output);
}
}*/
for (int i = 0; i < permutation.size(); i++) {
//if (permutation.get(i).get(0) > 0 && permutation.get(i).get(0) < 3 ){
List<Integer> k = permutation.get(i);
//System.out.println("Sorted :" + k);
int hh = k.get(0)*10 + k.get(1);
if (hh < 24) {
exists = true;
if (hh > h) {
h = hh;
}
}
int mm = k.get(2)*10 + k.get(3);
if ( mm < 60) {
exists = true;
if (mm > m) {
m = mm;
}
}
}
return (exists ? String.format("%02d:%02d", h, m) : "NOT POSSIBLE");
}
public static List<List<Integer>> permute(int[] num) {
List<List<Integer>> result = new ArrayList<>();
//start from an empty list
result.add(new ArrayList<>());
for (int i = 0; i < num.length; i++) {
//list of list in current iteration of the array num
List<List<Integer>> current = new ArrayList<>();
for (List<Integer> l : result) {
// # of locations to insert is largest index + 1
for (int j = 0; j < l.size()+1; j++) {
// + add num[i] to different locations
l.add(j, num[i]);
List<Integer> temp = new ArrayList<>(l);
current.add(temp);
//System.out.print(temp + " ");
//l.remove(num[i]);
l.remove(j);
}
}
result = new ArrayList<>(current);
}
return result;
}
}
最佳答案
您需要重新构建 h 和 m max 的测试。您当前的代码独立地查找每个的最大值。您得到的是最大小时和最大分钟,即使它们没有以排列方式同时出现,例如 20:42。
这是测试的工作版本。
int hh = k.get(0) * 10 + k.get(1);
if (hh < 24)
{
if (hh >= h)
{
int mm = k.get(2) * 10 + k.get(3);
if (mm < 60)
{
exists = true;
if (hh > h || mm > m)
{
m = mm;
}
h = hh;
}
}
}
请注意,hh>h
已变为 hh>=h
。即使该小时等于我们之前见过的小时,我们也需要寻找最大分钟。检查最大分钟的代码已移至小时测试的 if 子句内。我们需要确保我们正在考虑的分钟与最大小时相关联。最后,我们需要在 mm>m
时更新最大分钟,或者我们有一个新的最大小时 hh>h
通过此更改,您的代码将给出预期值:20:40
关于java - 最大有效时间由 4 位数字组成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45408217/