通过排列四个给定数字找到最大可能时间 HH:MM

2024-05-22

我最近为了工作晋升而参加了编码测试。这是我真正遇到的任务之一,我想知道什么是最好的方法来做到这一点。我使用了大量的 if 和 if else,这不是最干净的解决方案,但完成了工作。

我被问到的问题是:

将 4 个数字格式化为 24 小时时间 (00:00),查找可能的最大(最晚)时间,同时考虑到最大小时数为 23,最大分钟数为 59。如果不可能,则返回 NOT POSSIBLE。

例如:

6, 5, 2, 0 将是 20:56

3, 9, 5, 0 将是 09:53

7、6、3、8 是不可能的

必须返回时间或字符串的示例函数如下所示,A、B、C、D 与上面的逗号分隔列表中的数字不同:

function generate(A, B, C, D) {
    // Your code here
} 

人们将如何解决这个问题?


这是我想出的一个非暴力解决方案。查看代码中的注释以了解其工作原理。如果有任何不清楚的地方我可以帮助澄清。

function generate(A, B, C, D) {
    vals = [A, B, C, D];
    counts = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    for (i = 0; i < vals.length; i++) {
        for (j = vals[i]; j < counts.length; j++) counts[j]++;
    }
    // counts is now populated with the number of values less than or equal to the index it belongs to
    // so counts[2] is the total number of 0's, 1's and 2's
    if (counts[2] === 0) return 'NOT POSSIBLE';
    // if there are no 0's and 1's, then it must start with 2
    mustStartWith2 = counts[1] === 0;
    if (mustStartWith2 && counts[3] === 1) return 'NOT POSSIBLE';
    // We want a count of the number of free digits that are 5 or less (for the minute digit)
    numbersAvailableForMinute = counts[5] - (mustStartWith2 ? 2 : 1); 
    if (numbersAvailableForMinute === 0) return 'NOT POSSIBLE';
    // we now know that it is a valid time
    time = [0, 0, 0, 0];
    // we also know if it starts with 2
    startsWith2 = mustStartWith2 || (numbersAvailableForMinute >= 2 && counts[2] > counts[1]);
    // knowing the starting digit, we know the maximum value for each digit
    maxs = startsWith2 ? [2, 3, 5, 9] : [1, 9, 5, 9];
    for (i = 0; i < maxs.length; i++) {
        // find the first occurrence in counts that has the same count as the maximum
        time[i] = counts.indexOf(counts[maxs[i]]);
        // update counts after the value was removed
        for (j = time[i]; j < counts.length; j++) counts[j]--;
    }
    // create the time
    return time[0]+""+time[1]+":"+time[2]+""+time[3];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过排列四个给定数字找到最大可能时间 HH:MM 的相关文章

随机推荐