我遇到了这个问题陈述,其中两个时段(上午 9 点至下午 5 点)之间按排序顺序给出了 N 个时间段。{ \'start\':\'09:15\', \'duration\': 30 }, {&...
我遇到了这个问题陈述
{ "start": "09:15", "duration": 30 },
{ "start": "10:00", "duration": 60 },
{ "start": "11:15", "duration": 30 },
{ "start": "12:45", "duration": 30 },
{ "start": "13:15", "duration": 90 },
{ "start": "15:00", "duration": 30 },
{ "start": "15:30", "duration": 30 }
p2
p3
我相信最简单的算法(即传递输入并计算空闲槽)应该可以解决这个问题(下面的代码)。这应该具有 O(N) 时间复杂度和 O(1) 空间复杂度。
我问这个问题,是否有更好的算法来解决这类问题。
public static int findMaxSlots(JSONArray appointments) {
int result=0;
int prevTimeInMins = 540; //initialize with 9am minutes
String beginTime = "9:00";
String endOfDayTime = "17:00";
String startTime;
Long duration;
int len = appointments.size();
//this takes care of gap from 9am to first input(if any)
Integer beginMinutes = getMinutes(beginTime);
JSONObject appt = (JSONObject) appointments.get(0);
startTime = (String)appt.get("start");
if(getMinutes(startTime)-beginMinutes>0) {
result+=((getMinutes(startTime)-beginMinutes)/30);
System.out.println("result begin" + result);
}
//calculate for regular appointments
for (int i = 0; i < appointments.size(); i++) {
appt = (JSONObject) appointments.get(i);
startTime = (String)appt.get("start");
duration = (Long)appt.get("duration");
Integer mins = getMinutes(startTime);//555mins
System.out.println("mins loop" + mins);
if(mins-prevTimeInMins>30) {
result+=((mins-prevTimeInMins)/30);
prevTimeInMins=mins+ duration.intValue();
}
System.out.println("result loop" + result);
}
//this takes care of gap from last input to 5pm(if any)
Integer endMinutes = getMinutes(endOfDayTime);
appt = (JSONObject) appointments.get(len-1);
startTime = (String)appt.get("start");
duration = (Long)appt.get("duration");
Integer lastApptMins = getMinutes(startTime) + duration.intValue();
if(endMinutes-lastApptMins>0) {
result+=((endMinutes-lastApptMins)/30);
System.out.println("result end" + result);
}
return result;
}
private static int getMinutes(String startTime) {
String[] times = startTime.split(":");
int minutes = Integer.MIN_VALUE;
//15:00 -> 900minutes, 15:30 -> 930minutes
minutes = Integer.parseInt(times[0])*60;
minutes += Integer.parseInt(times[1]);
return minutes;
}
谢谢。