获得最小时差 [英] Getting minimum time difference
本文介绍了获得最小时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最近在一次编程采访中有人问我这个问题.我用HH:MM格式给出了一系列的时间.我需要找到以分钟为单位的最小时间差.时间本质上是循环的,因此23:55和00:12应当相差17.该功能还需要像24:00一样处理00:00(自然这是最简单的部分).有人可以帮助我开始解决这个问题.
I was asked this question recently in a coding interview. I'm given a series of times in HH:MM format. I need to find the minimum time difference in minutes. The time is circular in nature, thus 23:55 and 00:12 should have a difference of 17. The function also needs to handle 00:00 as the same thing as 24:00(this is the easiest part, naturally). Can someone help me get started with the problem.
推荐答案
您可以尝试以下方法:
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
String times[] = {"2:30","00:00", "00:12", "24:00", "23:55"};/*input times*/
int countTime = times.length;
int sortedTimes[] = new int[countTime];/*will hold sorted times*/
for (int i = 0; i < countTime; i++) {/*convert 'HH:mm' to integer minute*/
int t = Integer.valueOf(times[i].split(":")[0])*60
+ Integer.valueOf(times[i].split(":")[1]);
sortedTimes[i] = t;
}
Arrays.sort(sortedTimes);/*sort times*/
/*variables to hold the result*/
int minDiff = 1440;
int minT1 = 1440;
int minT2 = 1440;
for (int i = 0; i < countTime; i++) {
int curr = sortedTimes[i];
int prev = sortedTimes[(countTime+i-1)%countTime];
int diffPrev = Math.abs(curr - prev) < 1440 - Math.abs(curr - prev ) ?
Math.abs(curr - prev) : 1440 - Math.abs(curr - prev ) ;
if (minDiff > diffPrev) {
minDiff = diffPrev;
minT1 = prev;
minT2 = curr;
}
}
System.out.println("Minimum diff in minute: " + minDiff
+ " between " + (minT1/60 + ":" + minT1%60)
+ " and " + (minT2/60 + ":" + minT2%60));
}
}
这篇关于获得最小时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文