Open azl397985856 opened 3 years ago
与leetcode401.二进制手表有点像。
先统一转为分钟数, 然后分几类情况进行考虑。
先统一转为分钟数, 然后分几类情况进行讨论:
case: ["00:47", "00:57"]
["20:00", "06:00"]
, 包括了 00:00, 结束时间转为分钟数之后还需要加上24*60
class Solution {
public:
int numberOfRounds(string startTime, string finishTime) {
int startMinu = getMinutes(startTime);
int endMinu = getMinutes(finishTime);
if (endMinu < startMinu) endMinu += 24*60; /* case: ["20:00", "06:00"], 包括了 00:00 */
else if (endMinu - startMinu < 15) return 0; /* case: ["00:47", "00:57"] */
int validStart = startMinu % 15 != 0 ? (startMinu/15 + 1)*15 : startMinu/15*15;
int validEnd = endMinu/15*15;
return (validEnd - validStart)/15;
}
int getMinutes(string ts)
{
int hour = stoi(ts.substr(0, 2));
int minute = stoi(ts.substr(3, 2));
return 60*hour + minute;
}
};
public int numberOfRounds(String startTime, String finishTime) {
int startHH = Integer.parseInt(startTime.substring(0,2));
int startMM = Integer.parseInt(startTime.substring(3));
int endHH = Integer.parseInt(finishTime.substring(0,2));
int endMM = Integer.parseInt(finishTime.substring(3));
if(startHH == endHH && endMM - startMM > 0 && endMM - startMM < 15){
return 0;
}
int startIndex = startHH * 4 + (startMM + 14) / 15;
int endIndex = endHH * 4 + endMM / 15;
if(endIndex < startIndex){
return 96 - startIndex + endIndex;
}
return endIndex - startIndex;
}
class Solution {
public int numberOfRounds(String startTime, String finishTime) {
String[] startTimes = startTime.split(":");
String[] finishTimes = finishTime.split(":");
int startHour = Integer.parseInt(startTimes[0]);
int finishHour = Integer.parseInt(finishTimes[0]);
int startMinute = Integer.parseInt(startTimes[1]);
int finishMinute = Integer.parseInt(finishTimes[1]);
int count = 0;
if (startHour < finishHour) {
count += ((finishHour - startHour - 1) << 2);
} else if (startHour == finishHour) {
if (startMinute < finishMinute) {
count -= 4;
} else {
count += (23 << 2);
}
} else {
count += ((23 + finishHour - startHour) << 2);
}
count += getStartMinuteCount(startMinute);
count += getFinishMinuteCount(finishMinute);
return count > -1 ? count : 0;
}
private int getFinishMinuteCount(Integer finishMinute) {
if (finishMinute < 15) {
return 0;
} else if (finishMinute < 30) {
return 1;
} else if (finishMinute < 45) {
return 2;
}
return 3;
}
private int getStartMinuteCount(Integer startMinute) {
if (startMinute == 0) {
return 4;
} else if (startMinute <= 15) {
return 3;
} else if (startMinute <= 30) {
return 2;
} else if (startMinute <= 45) {
return 1;
}
return 0;
}
}
复杂度分析
令 n 为数组长度。
Convert the time into minutes then count how many 15min windows are contained in the interval. To handle edge cases easier:
O(1), O(1)
class Solution:
def numberOfRounds(self, st: str, ft: str) -> int:
hs, ms = list(map(int, st.split(":")))
he, me = list(map(int, ft.split(":")))
def tomins(hs, ms):
return hs*60 + ms
def helper(hs, ms, he, me):
mh = ceil(tomins(hs, ms)/15)*15
me = floor(tomins(he, me)/15)*15
return max((me - mh) // 15, 0)
if he < hs or (he == hs and me < ms):
return helper(hs, ms, 24, 0) + helper(0,0, he,me)
return helper(hs, ms, he, me)
模拟,记录经过的时间节点,最后减1得到时间节点组成的段落数。如果通宵,直接将结束时间增加24小时。
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
now=startTime
m=int(now[3:])
h=int(now[:2])
while m%15!=0:
m+=1
if m==60:
m=0
h+=1
endh=int(finishTime[:2])
endm=int(finishTime[3:])
if startTime>finishTime:
endh+=24
c=0
while h<endh or (h==endh and m<=endm):
c+=1
m+=15
if m==60:
m=0
h+=1
if c==0:
return 0
return c-1
时间复杂度:O(1)
空间复杂度:O(1)
转换为分钟直接算,时间更稳定
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
t1=int(startTime[:2])*60+int(startTime[3:])
t2=int(finishTime[:2])*60+int(finishTime[3:])
if t1>t2:
t2+=60*24
if t1%15==0:
point1=t1//15
else:
point1=t1//15+1
point2=t2//15
if point1>=point2:
return 0
return point2-point1
class Solution(object):
def numberOfRounds(self, startTime, finishTime):
def normalizeStart(startMinute):
if startMinute == 0:
return 0
if 0 < startMinute <= 15:
return 15
elif 15 < startMinute <= 30:
return 30
elif 30 < startMinute <= 45:
return 45
elif 45 < startMinute:
return 60
def normalizeEnd(endMinute):
if endMinute == 0:
return 0
if 0 <= endMinute < 15:
return 0
elif 15 <= endMinute < 30:
return 15
elif 30 <= endMinute < 45:
return 30
elif 45 <= endMinute:
return 45
start = startTime.split(':')
end = finishTime.split(':')
startHour, startMinute= int(start[0]),int(start[1])
endHour, endMinute= int(end[0]), int(end[1])
result = 0
if startHour == endHour:
if startMinute > endMinute:
startM , endM = normalizeStart(startMinute), normalizeEnd(endMinute)
return max(0,((endHour*60+endM)-(0)+(23*60+60)-(startHour*60+startM))/15)
startM , endM = normalizeStart(startMinute), normalizeEnd(endMinute)
return max(0,(endM-startM)/15)
elif startHour < endHour:
startM , endM = normalizeStart(startMinute), normalizeEnd(endMinute)
return max(0,((endHour*60+endM)-(startHour*60+startM))/15)
else:
startM , endM = normalizeStart(startMinute), normalizeEnd(endMinute)
return max(0, ((endHour*60+endM)-(0)+(23*60+60)-(startHour*60+startM))/15)
class Solution {
public int numberOfRounds(String startTime, String finishTime) {
int startMinutes = getMinutes(startTime);
int endMinutes = getMinutes(finishTime);
return calculateRounds(startMinutes, endMinutes);
}
private int getMinutes(String time) {
String[] array = time.split(":");
int[] t = new int[2];
t[0] = Integer.parseInt(array[0]);
t[1] = Integer.parseInt(array[1]);
return t[0] * 60 + t[1];
}
private int calculateRounds(int start, int end) {
if (end < start) {
end += 24 * 60;
}
int res = (int) Math.floor(end / 15D) - (int) Math.ceil(start / 15D);
return res < 0 ? 0 : res;
}
}
hour和minute分开算,然后相加。送分
fun numberOfRounds(startTime: String, finishTime: String): Int {
val (sh, sm) = startTime.split(":", limit = 2).map { it.toInt() }
val (fh, fm) = finishTime.split(":", limit = 2).map { it.toInt() }
val hours = if (sh > fh || (sh == fh && sm > fm)) fh + 24 - sh else fh - sh
val quarts = floor(fm / 15.0).toInt() - ceil(sm / 15.0).toInt()
val res = hours * 4 + quarts
return if (res >= 0) res else 0
}
时间复杂度:O(n) 空间复杂度:O(1)
class Solution {
public int numberOfRounds(String startTime, String finishTime) {
int start = getTime(startTime);
int end = getTime(finishTime);
int total = 0;
if (end < start) {
total += 1440 / 15 - start / 15;
if (start % 15 != 0) total -= 1;
total += end / 15;
} else {
total = end / 15 - start / 15;
if (start % 15 != 0) total -= 1;
}
return total < 0 ? 0 : total;
}
private int getTime(String time) {
int hour = Integer.parseInt(time.substring(0, 2));
int minute = Integer.parseInt(time.substring(3));
return hour * 60 + minute;
}
}
LC 1904. The Number of Full Rounds You Have Played
Ideas
comment Runtime: 49 ms, faster than 13.64%
python代码
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
sh, sm = int(startTime.split(':')[0]),int(startTime.split(':')[1])
fh,fm = int(finishTime.split(':')[0]),int(finishTime.split(':')[1])
t0 = 60*sh + sm
t1 = 60*fh + fm
if t0>t1:
t1 = t1+60*24
t1 = t1//15*15
if t1-t0 < 15:
return 0
else:
return (t1-t0)//15
复杂度分析
class Solution: def numberOfRounds(self, startTime: str, finishTime: str) -> int:
def getMins(time):
hour,minunite = time.split(":")
return int(hour)*60 + int(minunite)
startMinutes = getMins(startTime)
endMinutes = getMins(finishTime)
start15s = startMinutes//15 if startMinutes%15==0 else startMinutes//15+1
end15s = endMinutes//15
if startMinutes > endMinutes:
end15s += 60*24/15
if start15s>end15s:
return 0
else:
return int(end15s - start15s)
time: O(1) space: O(1)
class Solution {
public int numberOfRounds(String startTime, String finishTime) {
String[] startArray = startTime.split(":"), finishArray = finishTime.split(":");
int[] start = new int[]{Integer.parseInt(startArray[0]), Integer.parseInt(startArray[1])};
int[] end = new int[]{Integer.parseInt(finishArray[0]), Integer.parseInt(finishArray[1])};
if (end[0] < start[0] || (end[0] == start[0] && start[1] > end[1])){
end[0] += 24;
}
start[1] = (start[1] + 15 - 1) / 15;
if (start[1] == 4){
start[1] = 0;
start[0]++;
}
end[1] /= 15;
if (end[1] < start[1]){
end[1] += 4;
end[0]--;
}
int result = end[1] - start[1] + (end[0] - start[0]) * 4;
return result > 0 ? result : 0;
}
}
Time Complexity: O(1), Space Complexity: O(1)
like manually calcualte
Time: O(1) Space: O(1)
class Solution {
public int numberOfRounds(String startTime, String finishTime) {
int count=0;
int startH= Integer.parseInt(startTime.substring(0,2));
int startM= Integer.parseInt(startTime.substring(3,5));
int endH= Integer.parseInt(finishTime.substring(0,2));
int endM= Integer.parseInt(finishTime.substring(3,5));
int startT=startH*100+startM;
int endT=endH*100+endM;
startM=floorstart(startM);
endM=floorend(endM);
if(startT>endT) {
endH+=24;
if(startM>endM) {
endH--;
endM+=60;
}
}
else {
if(endM-startM<0) {
endM+=60;
endH--;
}
if(endH-startH<0)
return 0;
}
count=(endM-startM)/15+(endH-startH)*4;
return count;
}
private int floorstart(int num) {
if(num>0 && num<15)
num=15;
else if(num>15 && num<30)
num=30;
else if(num>30 && num<45)
num=45;
else if(num>45 && num<60)
num=60;
return num;
}
private int floorend(int num) {
if(num>0 && num<15)
num=0;
else if(num>15 && num<30)
num=15;
else if(num>30 && num<45)
num=30;
else if(num>45 && num<60)
num=45;
return num;
}
}
m1
, h1
, m2
, h2
。 m1
,m2
对齐到 00,15,30,45,60 。diff_res
, diff_res / 15
即为结果。class Solution {
public:
int numberOfRounds(string startTime, string finishTime) {
int h1, m1, h2, m2;
h1 = stoi(startTime.substr(0,2));
m1 = stoi(startTime.substr(3, 2));
h2 = stoi(finishTime.substr(0, 2));
m2 = stoi(finishTime.substr(3, 2));
if(h2 < h1 || h2 == h1 && m2 < m1){
h2 += 24;
}
m1 = (m1 + 14) / 15 * 15;
if(m1 == 60){
m1 = 0;
h1 ++;
}
m2 = m2 / 15 * 15;
int diff_res = 0;
if(m2 < m1){
h2 --;
m2 += 60;
}
diff_res = (h2 - h1) * 60 + m2 - m1;
if(diff_res <= 0){
return 0;
}
return diff_res / 15;
}
};
n为字符串长度
# cal start/end time in minutes
# round start to next start time
# round end time to previous end time
# if start time < end time: (end - start) / 15
# return (24 * 60 - (start - end)) / 15
# note: edge cases where start time < end time and rounded start time >= rounded end time
# (22:46, 23:01), (22:50, 22:56), this should return 0
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
start_minutes = self.to_minutes(startTime)
end_minutes = self.to_minutes(finishTime)
rounded_start = self.to_next_quarter(start_minutes)
rounded_end = self.to_prev_quarter(end_minutes)
if start_minutes < end_minutes and rounded_start >= rounded_end:
return 0
if rounded_start < rounded_end:
return (rounded_end - rounded_start) // 15
return (24 * 60 - rounded_start + rounded_end) // 15
def to_minutes(self, time):
hours = int(time[0:2]) * 60
minutes = int(time[3:])
return hours + minutes
def to_next_quarter(self, minutes):
return ((minutes + 14) // 15) * 15
def to_prev_quarter(self, minutes):
return (minutes // 15) * 15
Explanation
Python
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
def getTime(t):
h, m = t.split(":")
return int(h) * 60 + int(m)
start = getTime(startTime)
finish = getTime(finishTime)
if finish < start:
finish += 24 * 60
start = (start + 14) // 15 * 15
finish = finish // 15 * 15
return (finish-start) // 15 if finish > start else 0
Complexity:
O(n)
O(1)
C++ Code:
class Solution {
public:
int numberOfRounds(string startTime, string finishTime) {
int startMin = minTime(startTime);
int endMin = minTime(finishTime);
if(endMin < startMin)
endMin += (24*60);
int startQauter = ceil( double(startMin)/15.0);
int endQauter = floor(double(endMin)/15.0);
return endQauter - startQauter>=0 ? endQauter - startQauter: 0;
}
int minTime(string& Time)
{
int hour =0;
int min =0;
int left =0;
bool ihour = true;
while(left< Time.size())
{
if(Time[left]==':')
{
ihour = false;
}
else
{
if(ihour == true)
{
hour= hour*10 + (Time[left]-'0');
}
else
{
min = min*10 + (Time[left]-'0');
}
}
left++;
}
return 60*hour + (min);
}
};
class Solution {
public int numberOfRounds(String startTime, String finishTime) {
// 分别获得startTime和finishTime的小时和分钟
int startHH = Integer.parseInt(startTime.substring(0,2));
int startMM = Integer.parseInt(startTime.substring(3));
int finishHH = Integer.parseInt(finishTime.substring(0,2));
int finishMM = Integer.parseInt(finishTime.substring(3));
int round = 0;
// 时长不足15分钟
if(startHH == finishHH && finishMM - startMM > 0 && finishMM - startMM < 15){
round = 0;
}
// 时长不足一小时
else if (startHH == finishHH && finishMM - startMM > 0 && finishMM - startMM < 60) {
round = finishMM / 15 - (startMM + 14) / 15;
}
// 过了一晚
else if (finishHH < startHH || (finishHH == startHH && startMM > finishMM)) {
round = (finishHH + 24 - startHH) * 4 + finishMM / 15 - (startMM + 14) / 15;
}
// 时长超过一小时,且没过一晚
else {
round = (finishHH - startHH) * 4 + finishMM / 15 - (startMM + 14) / 15;
}
return round;
}
}
public int numberOfRounds(String startTime, String finishTime) {
int startHr = Integer.parseInt(startTime.split(":")[0]);
int startMin = Integer.parseInt(startTime.split(":")[1]);
int start = startHr * 60 + startMin;
int endHr = Integer.parseInt(finishTime.split(":")[0]);
int endMin = Integer.parseInt(finishTime.split(":")[1]);
int end = endHr * 60 + endMin;
if (start > end) end += 24 * 60;
return Math.max(0, (int) Math.floor(end / 15.00) - (int) Math.ceil(start / 15.00));
}
Time: O(1) Space: O(1)
class Solution {
public int numberOfRounds(String startTime, String finishTime) {
String[] arr1 = startTime.split(":"), arr2 = finishTime.split(":");
int hour1 = Integer.parseInt(arr1[0]), minute1 = Integer.parseInt(arr1[1]), hour2 = Integer.parseInt(arr2[0]), minute2 = Integer.parseInt(arr2[1]);
if (hour1 > hour2 || (hour1 == hour2 && minute1 > minute2)) {
hour2 += 24;
}
int ret = 0;
if (hour2 - hour1 >= 1) {
ret += (hour2 - hour1 - 1) * 4;
ret += (60 - minute1) / 15 + minute2 / 15;
}
else {
ret += (60 - minute1) / 15 - (60 - minute2) / 15;
if (ret > 0 && minute2 % 15 != 0) {
ret -= 1;
}
}
return ret;
}
}
class Solution(object):
def numberOfRounds(self, startTime, finishTime):
"""
:type startTime: str
:type finishTime: str
:rtype: int
"""
startHour, startMin = [int(item) for item in startTime.split(":")]
finishHour, finishMin = [int(item) for item in finishTime.split(":")]
res = 0
games = [0, 15, 30, 45]
if startHour > finishHour or (startHour == finishHour and startMin>finishMin):
return self.numberOfRounds(startTime, str(24)+":00") + self.numberOfRounds("00:00", finishTime)
start = 0
while start<4 and startMin > games[start]:
start += 1
end = 3
while end >=0 and finishMin < games[end]:
end -= 1
if startHour == finishHour:
return max(0, end-start)
elif finishHour>startHour:
return (4-start)+end+(finishHour-1-startHour)*4
var numberOfRounds = function (startTime, finishTime) {
const start =
parseInt(startTime.slice(0, 2)) * 4 +
Math.ceil(parseInt(startTime.slice(3, 5)) / 15);
const finish =
parseInt(finishTime.slice(0, 2)) * 4 +
Math.floor(parseInt(finishTime.slice(3, 5)) / 15);
return startTime < finishTime
? Math.max(0, finish - start)
: finish - start + 96;
};
模拟。
class Solution {
public:
int numberOfRounds(string startTime, string finishTime) {
int start = stoi(startTime.substr(0, 2)) * 60 + stoi(startTime.substr(3, 5));
int finish = stoi(finishTime.substr(0, 2)) * 60 + stoi(finishTime.substr(3, 5));
if (start > finish) finish += 1440;
finish = finish / 15 * 15;
return max(0, (finish - start) / 15);
}
};
思路:
模拟法 复杂度分析:
代码(C++):
class Solution {
public:
int numberOfRounds(string startTime, string finishTime) {
int start = convertTime(startTime);
int finish = convertTime(finishTime);
// overnight
if (finish < start) {
finish += 24 * 60;
} else if (finish - start < 15)
return 0;
int c1 = (start % 15 == 0) ? start / 15: start / 15 + 1;
int c2 = finish / 15;
return c2 - c1;
}
private:
int convertTime(string time) {
int h = stoi(time.substr(0, 2));
int m = stoi(time.substr(3, 2));
return h * 60 + m;
}
};
class Solution(object):
def numberOfRounds(self, startTime, finishTime):
"""
:type startTime: str
:type finishTime: str
:rtype: int
"""
# tc: O(1)
sh,sm = int(startTime.split(':')[0]), int(startTime.split(':')[1])
eh,em = int(finishTime.split(':')[0]),int(finishTime.split(':')[1])
st = 60*sh + sm
et = 60*eh + em
# 通宵
if et < st:
et += 60*24
et = (et//15) *15
ans = max(0,(et-st)//15)
return ans
算出开始和结束时刻经过的15分钟数,然后处理通宵情况
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
if startTime == finishTime:
return 0
startTimeList = startTime.split(':')
finishTimeList = finishTime.split(':')
startTimeNumber = 60 * int(startTimeList[0]) + int(startTimeList[1])
finishTimeNumber = 60 * int(finishTimeList[0]) + int(finishTimeList[1])
if(0 < finishTimeNumber - startTimeNumber < 15):
return 0
startTimeRound = ceil(startTimeNumber / 15)
finishTimeRound = floor(finishTimeNumber / 15)
round = finishTimeRound - startTimeRound if finishTimeNumber > startTimeNumber else finishTimeRound + (96 - startTimeRound)
return round
时间复杂度 :O(1)
空间复杂度:O(1)
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
sh, sm = map(int, startTime.split(":"))
eh, em = map(int, finishTime.split(":"))
if 0 < sm < 15:
sm = 15
elif 15 < sm < 30:
sm = 30
elif 30 < sm < 45:
sm = 45
elif 45 < sm < 60:
sm = 0
sh += 1
if 0 < em < 15:
em = 0
elif 15 < em < 30:
em = 15
elif 30 < em < 45:
em = 30
elif 45 < em < 60:
em = 45
st = sh * 60 + sm
et = eh * 60 + em
if st > et:
et += 24 * 60
return (et - st) // 15
计算startTime 和 finishTime之间有多少个15分钟
def normalize(start_time, end_time):
end_hour, end_minutes = int(end_time[0:2]), int(end_time[3:])
start_hour, start_minuts = int(start_time[0:2]), int(start_time[3:])
if end_hour < start_hour:
end_hour += 24
elif end_hour == start_hour and end_minutes < start_minuts:
end_hour += 24
return start_hour, start_minuts, end_hour, end_minutes
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
start_hour, start_minutes, end_hour, end_minutes = normalize(
startTime, finishTime
)
total_game = (
(end_hour - start_hour) * 4
- start_minutes // 15
- (1 if start_minutes % 15 > 0 else 0)
+ end_minutes // 15
)
return max(total_game, 0)
Time O(1)
Space O(1)
正则匹配时间,将时间转换为分钟表示,将通宵时间+1440分钟,计算开始和结束时间所在的刻钟数,相减。需要注意处在相同刻钟数时会产生负数结果,返回时需消除。
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
matchobj=re.match(r'(\d+):(\d+)',startTime)
startm=int(matchobj.group(1))*60
startm+=int(matchobj.group(2))
matchobj=re.match(r'(\d+):(\d+)',finishTime)
finishm=int(matchobj.group(1))*60
finishm+=int(matchobj.group(2))
if finishm<startm:
finishm+=1440
res=math.floor(float(finishm)/15)-math.ceil(float(startm)/15)
return res if res>-1 else 0
Deal with edge cases
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
start_hour = int(startTime[:2])
start_minute = int(startTime[3:])
finish_hour = int(finishTime[:2])
finish_minute = int(finishTime[3:])
if finish_hour < start_hour or ((finish_hour == start_hour) and (start_minute > finish_minute)): finish_hour += 24
start_hour, start_minute = self.trim_minute(True, start_hour, start_minute)
finish_hour, finish_minute = self.trim_minute(False, finish_hour, finish_minute)
res = (finish_hour-start_hour) * 60 + finish_minute - start_minute
return max(res//15,0)
def trim_minute(self, start, hour, minute):
if start:
if minute == 0: minute = 0
elif minute<=15: minute = 15
elif minute<=30: minute = 30
elif minute<=45: minute = 45
else:
minute = 0
hour+=1
else:
if minute<15: minute = 0
elif minute<30: minute = 15
elif minute<45: minute = 30
else: minute = 45
return hour, minute
Space: O(1) Time: O(S+S)
转化为分钟数,进行数学处理。
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
start_hour, start_min = startTime.split(':')
finish_hour, finish_min = finishTime.split(':')
if int(start_hour)>int(finish_hour):
finish_hour = int(finish_hour)+24
elif int(start_hour) == int(finish_hour):
if int(start_min)> int(finish_min):
finish_hour = int(finish_hour)+24
total_time = (int(finish_hour)-int(start_hour))*60+(int(finish_min)-int(start_min))
if int(start_min)%15!=0:
total_time-=(15-int(start_min)%15)
return 0 if total_time <15 else total_time//15
复杂度分析
https://leetcode.com/problems/the-number-of-full-rounds-you-have-played/
const numberOfRounds = function (startTime, finishTime) {
let start =
60 * parseInt(startTime.slice(0, 2)) + parseInt(startTime.slice(3));
let end =
60 * parseInt(finishTime.slice(0, 2)) + parseInt(finishTime.slice(3));
if (start > end) end += 24 * 60;
return Math.max(0, Math.floor(end / 15) - Math.ceil(start / 15));
};
O(1)
模拟。先把时间从String转化为int。在判断finishTime是否大于startTime,如果不是,finishTime加上24。然后把开始时间向上计算得到最接近的15分钟,把结束时间向下计算得到最接近的15分钟。按照分钟差值计算对局数。注意edge case:时间相隔不到15分钟,按照此法计算最后会得-1,需要改为0。
class Solution {
public int numberOfRounds(String startTime, String finishTime) {
int shour = Integer.parseInt(startTime.substring(0, 2));
int smin = Integer.parseInt(startTime.substring(3));
int fhour = Integer.parseInt(finishTime.substring(0, 2));
int fmin = Integer.parseInt(finishTime.substring(3));
if (fhour == shour && fmin < smin) fhour += 24;
if (fhour < shour) fhour += 24;
smin = (smin + 14) / 15 * 15;
if (smin == 60) {
smin = 0;
shour++;
}
fmin = fmin / 15 * 15;
int total = (fhour - shour) * 60 + fmin - smin;
return total >= 0 ? total / 15 : 0;
}
}
复杂度分析
Calculate how many game you can play from start to end, if it's start:00 and end:00. Then delete the game you cannot play due to the minutes part of starttime. The number should be ceiled. After than add the extra game you can play due to the minute part of endtime. The number should be floored. If the final answer is negative, return 0
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
start = startTime.split(":")
end = finishTime.split(":")
start =[int(start[0]), int(start[1])]
end =[int(end[0]), int(end[1])]
if start[0] > end[0] or (start[0] == end[0] and start[1] > end[1]):
end[0] += 24
ans = 0
ans += (end[0] - start[0]) * 4
ans -= start[1]//15
if start[1] % 15 > 0:
ans -= 1
ans += end[1] // 15
return max(ans, 0)
Time: O(1) Space: O(1)
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
start = startTime.split(':')
start = [int(i) for i in start]
fin = finishTime.split(':')
fin = [int(i) for i in fin]
if start[0] == fin[0]:
if start[1] == fin[1]: # overnight
overnight = 1
elif start[1] < fin[1]: # no overnight
overnight = 0
elif start[1] > fin[1]: # overnight
overnight = 1
elif start[0] > fin[0]:
overnight = 1
else:
overnight = 0
res = 0
if overnight == 0:# no overnight
start_t = (start[1]//15 + ((start[1]%15)>0))*15
fin_t = (fin[1]//15)*15
res = (fin[0] - start[0])*4 + (fin_t - start_t )//15
else:
#overnight
start_t = (start[1]//15 + ((start[1]%15)>0))*15
fin_t = (fin[1]//15)*15
res1 = (23- start[0])*4 + (60 - start_t )//15
res2 = (fin[0])*4 + (fin_t)//15
res = res1 + res2
if res < 0:
return 0
return res
Problem Link
Ideas
Complexity: hash table and bucket
Code
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
# 转化为分钟
t0 = 60 * int(startTime[:2]) + int(startTime[3:])
t1 = 60 * int(finishTime[:2]) + int(finishTime[3:])
if t1 < t0:
# 此时 finishTime 为第二天
t1 += 1440
# 第一个小于等于 finishTime 的完整对局的结束时间
t1 = t1 // 15 * 15
return max(0, (t1 - t0)) // 15
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
start_h, start_min = int(startTime.split(':')[0]), int(startTime.split(':')[1])
finish_h, finish_min = int(finishTime.split(':')[0]), int(finishTime.split(':')[1])
if finish_h*60 + finish_min< start_h*60 + start_min:
finish_h += 24
if finish_h*60 + finish_min - start_h*60 - start_min <15:
return 0
#"00:47" "00:57"
elif (finish_h*60 + finish_min - start_h*60 - start_min ==15) and (start_min% 15!=0):
return 0
#"11:00" "11:15"
else:
start_min = math.ceil(start_min/15)*15
finish_min = math.floor(finish_min/15)*15
#print (start_min, finish_min,finish_h, start_h, finish_h*60 + finish_min - start_h*60 + start_min)
return (finish_h*60 + finish_min - start_h*60 - start_min)//15
先将 开始时间 和 结束时间 转换成分钟数
如果 开始时间比结束时间 早点话, 代表通宵了, 所以要 + 24 * 60 分钟 到 结束时间
然后将结束时间 round 到 最接近的 15 分钟 ( time // 15 * 15)
eg. 12:03 → 12:00, 12:15 → 12:15
最后 的结果是 max(0, (finish-start) // 15), 因为可能有 12:47, 12:55 的 情况, 此时 12:55 会被 round 到 12:45, 会出现 负数的情况, 所以需要 跟 0 取 max
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
start_hour = int(startTime[:2])
finish_hour = int(finishTime[:2])
start_minutes = int(startTime[-2:])
finish_minutes = int(finishTime[-2:])
start = start_hour * 60 + start_minutes
finish = finish_hour * 60 + finish_minutes
if start > finish:
finish += 24 * 60
# round finish to the closest 15
finish = finish // 15 * 15
return max(0, (finish-start) // 15)
时间复杂度: O(1)
空间复杂度: O(1)
将时间转换为分钟。如果开始时间不能够被15整除,向上取整,结束时间向下取整
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
mstart = int(startTime[:2]) * 60 + int(startTime[3:])
mfinish = int(finishTime[:2]) * 60 + int(finishTime[3:])
output = 0
if mstart > mfinish:
mfinish += 60 * 24
# 如果mstart不能整除15,则要向上取整
if mstart % 15 == 0:
rstart = mstart // 15
else:
rstart = mstart // 15 + 1
# 结束时间要向下取整
rfinish = mfinish // 15
if rstart >= rfinish:
return 0
return rfinish - rstart
时间复杂度:O(1) 空间复杂度:O(1)
分别处理小时和分钟。先计算小时内完成的局数,再根据分钟调整。完整小时的计算,就是计算时间段内有几个完整的小时数,乘4,其中需要判断是否过了一天,根据case可以判断end小时比start小就是过了一天(根据badcase还有就是小时一样,但是end分钟比start分钟小也是!需要注意分析)然后看分钟,分钟分成start分钟和end分钟,end分钟看覆盖几个15,就加上去,start分钟分成能整除15和不能,能整除15,就减掉,不能就整除15的个数+1。不能直接减整除15,因为涉及开始是否过15的倍数和结束是否过15的倍数。(我感觉不能)
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
start_h = int(startTime[:2])
end_h = int(finishTime[:2])
start_min = int(startTime[-2:])
end_min = int(finishTime[-2:])
# 判断是否过了一天
if end_h < start_h:
h = 24-start_h+end_h
# 根据badcase可以总结,还有一种情况"00:01" "00:00"
elif end_h == start_h and end_min < start_min:
h = 24
else:
h = end_h - start_h
base_round = h * 4
if end_min > 0:
base_round += end_min // 15
if start_min > 0:
if start_min % 15 == 0:
base_round -= start_min // 15
else:
base_round -= (start_min // 15 + 1)
return base_round if base_round >= 0 else 0 # 由于是加上后面多的减掉前面少的,可能会有负数的
Language: Java
public int numberOfRounds(String startTime, String finishTime) {
int startHour = Integer.valueOf(startTime.substring(0, 2));
int startMin = Integer.valueOf(startTime.substring(3));
int finishHour = Integer.valueOf(finishTime.substring(0, 2));
int finishMin = Integer.valueOf(finishTime.substring(3));
if (startHour > finishHour || (startHour == finishHour && startMin > finishMin)) {
return numberOfRounds(startTime, "24:00") + numberOfRounds("00:00", finishTime);
}
startMin = startMin % 15 == 0 ? startMin : (startMin / 15 + 1) * 15;
finishMin = finishMin / 15 * 15;
int totalTime = (finishHour - startHour) * 60 + (finishMin - startMin);
return totalTime > 0 ? totalTime / 15 : 0;
}
https://leetcode-cn.com/problems/the-number-of-full-rounds-you-have-played/
记得处理通宵的情况,以及start要向上取整,finish要向下取整,start大于finish时说明游戏时间为0.
class Solution {
public int numberOfRounds(String startTime, String finishTime) {
int startHour = Integer.parseInt(startTime.split(":")[0]);
int startMinute = Integer.parseInt(startTime.split(":")[1]);
int finishHour = Integer.parseInt(finishTime.split(":")[0]);
int finishMinute = Integer.parseInt(finishTime.split(":")[1]);
int start = startHour * 60 + startMinute;
int finish = finishHour * 60 + finishMinute;
//开始时间大于结束时间,即为通宵了,需要加上一整天的时间
if(start > finish) {
finish += 24 * 60;
}
//开始时间要向上取整
start = (start + 14) / 15;
System.out.println("start : " + start);
//结束时间要向下取整
finish /= 15;
System.out.println("finish : " + finish);
return start > finish ? 0 : finish - start;
}
}
O(1)
O(1)
时间转为分钟。如果开始时间不够被14整除,向上取整,结束时间向下取整
class Solution {
public int numberOfRounds(String startTime, String finishTime) {
//转化分钟
int t0 = Integer.parseInt(startTime.substring(0, 1)) * 60 + Integer.parseInt(startTime.substring(2, 3));
int t1 = Integer.parseInt(finishTime.substring(0, 1)) * 60 + Integer.parseInt(finishTime.substring(2, 3));
if (t1 < t0) {
//此时为finishTime第二天
t1 += 1440;
}
// 第一个小于等于finishTime的完整对局的结束时间
t1 = t1 / 15 * 15;
return max(0, (t1 - t0)) / 15;
}
}
时分转换,考虑边界
class Solution {
public int numberOfRounds(String startTime, String finishTime) {
int startHH = Integer.parseInt(startTime.substring(0,startTime.indexOf(":")));
int finishHH = Integer.parseInt(finishTime.substring(0,finishTime.indexOf(":")));
int startMM = Integer.parseInt(startTime.substring(startTime.indexOf(":")+1));
int finishMM = Integer.parseInt(finishTime.substring(finishTime.indexOf(":")+1));
int HH = finishHH-startHH;
int nub = 0;
if(HH>0){
nub = getNub(startMM, nub);
nub=nub+(finishMM/15)+(HH-1)*4;
return nub;
}
if(HH==0){
if(startMM==finishMM){
return 96;
}
if(startMM<finishMM){
nub = getNub(startMM, nub);
nub= nub-4+(finishMM/15);
if(nub<0){
return 0;
}
return nub;
}
nub = getNub(startMM, nub);
nub= nub+(finishMM/15)+92;
return nub;
}
nub = getNub(startMM, nub);
nub=nub+(finishMM/15)+(HH+23)*4;
return nub;
}
private int getNub(int startMM, int nub) {
if(startMM==0){
nub=+4;
}else if(startMM==15){
nub=+3;
}else if(startMM==30){
nub=+2;
}else if(startMM==45){
nub=+1;
}else {
nub=nub+(3-startMM/15);
}
return nub;
}
}
将时间转换为分钟
var numberOfRounds = function(startTime, finishTime) {
//将时间拆成数组
let start=startTime.split(":").map(Number);
let finish=finishTime.split(":").map(Number);
//时间转换成分钟
let startMM=start[0]*60+start[1];
let finishMM=finish[0]*60+finish[1];
//结束时间小于开始时间,通宵加一天60*24
if(startMM>finishMM)finishMM+=1440;
return Math.max(0,Math.floor(finishMM/15)-Math.ceil(startMM/15))
};
class Solution {
public int numberOfRounds(String startTime, String finishTime) {
int startHH = Integer.parseInt(startTime.substring(0,startTime.indexOf(":")));
int finishHH = Integer.parseInt(finishTime.substring(0,finishTime.indexOf(":")));
int startMM = Integer.parseInt(startTime.substring(startTime.indexOf(":")+1));
int finishMM = Integer.parseInt(finishTime.substring(finishTime.indexOf(":")+1));
int HH = finishHH-startHH;
int nub = 0;
if(HH>0){
nub = getNub(startMM, nub);
nub=nub+(finishMM/15)+(HH-1)*4;
return nub;
}
if(HH==0){
if(startMM==finishMM){
return 96;
}
if(startMM<finishMM){
nub = getNub(startMM, nub);
nub= nub-4+(finishMM/15);
if(nub<0){
return 0;
}
return nub;
}
nub = getNub(startMM, nub);
nub= nub+(finishMM/15)+92;
return nub;
}
nub = getNub(startMM, nub);
nub=nub+(finishMM/15)+(HH+23)*4;
return nub;
}
private int getNub(int startMM, int nub) {
if(startMM==0){
nub=+4;
}else if(startMM==15){
nub=+3;
}else if(startMM==30){
nub=+2;
}else if(startMM==45){
nub=+1;
}else {
nub=nub+(3-startMM/15);
}
return nub;
}
}
class Solution
{
public:
int numberOfRounds(string startTime, string finishTime)
{
std::istringstream ssStartTime(startTime);
std::string token;
std::vector<int> sTime;
while (std::getline(ssStartTime, token, ':')) {
sTime.push_back(std::stoi(token));
}
std::istringstream ssFinishTime(finishTime);
std::vector<int> fTime;
while (std::getline(ssFinishTime, token, ':')) {
fTime.push_back(std::stoi(token));
}
// Increse the finishTime by one day if it is smaller than startTime
if (sTime[0] > fTime[0] || (sTime[0] == fTime[0] && sTime[1] >= fTime[1])) {
fTime[0] += 24;
}
// Round the startTime minutes up, round the finishTime minutes down
sTime[1] = std::ceil(sTime[1] / 15.f) * 15;
fTime[1] = std::floor(fTime[1] / 15.f) * 15;
int res{ 0 };
// After the rounding, there's no full-round game available
if (sTime[0] == fTime[0] && sTime[1] >= fTime[1]) {
res = 0;
} else {
res = (fTime[0] - sTime[0]) * 4 + (fTime[1] - sTime[1]) / 15;
}
return res;
}
};
将HH:mm转成分钟, 如果endTime < startTime; endTime+24h , endTime/15向下取整 - startTime/15向上取整
java
class Solution {
public int numberOfRounds(String startTime, String finishTime) {
int startMinutes = getMinutes(startTime);
int endMinutes = getMinutes(finishTime);
return calculateRounds(startMinutes, endMinutes);
}
private int getMinutes(String time) {
String[] array = time.split(":");
int[] t = new int[2];
t[0] = Integer.parseInt(array[0]);
t[1] = Integer.parseInt(array[1]);
return t[0] * 60 + t[1];
}
private int calculateRounds(int start, int end) {
if (end < start) {
end += 24 * 60;
}
int res = (int) Math.floor(end / 15D) - (int) Math.ceil(start / 15D);
if(res < 0){
return 0;
}else{
return res;
}
}
}
时间复杂度 O(n)
空间复杂度 O(1)
AC
class Solution {
public int numberOfRounds(String startTime, String finishTime) {
String[] start = startTime.split(":");
int sMin = Integer.valueOf(start[1]);
int rawSTime = Integer.valueOf(start[0])*60 + sMin;
sMin = sMin % 15 == 0?sMin:(sMin / 15 + 1) * 15;
int sTime = Integer.valueOf(start[0])*60 + sMin;
String[] finish = finishTime.split(":");
int fMin = Integer.valueOf(finish[1]);
int rawFTime = Integer.valueOf(finish[0])*60 + fMin;
fMin = fMin % 15 == 0?fMin:(fMin / 15) * 15;
int fTime = Integer.valueOf(finish[0])*60 + fMin;
int time = 0;
if(rawFTime < rawSTime){
time = (24 * 60 - sTime) + fTime;
} else {
time = fTime - sTime;
}
System.out.println((time));
int count = (time / 15);
return count < 0?0:count;
}
}
time: O(1) space: O(1)
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
startHour = int(startTime[:2])
finishHour = int(finishTime[:2])
s = startHour * 60 + int(startTime[-2:])
f = finishHour * 60 + int(finishTime[-2:])
if s > f:
finishHour += 24
start = (int(startTime[-2:]) + 14) // 15 * 15
finish = (int(finishTime[-2:]) // 15 * 15)
s = startHour * 60 + start
f = finishHour * 60 + finish
return max(0, (f - s) // 15)
1904. 你完成的完整对局数
https://leetcode-cn.com/problems/the-number-of-full-rounds-you-have-played/
转化为分钟
class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
# 转化为分钟
t0 = 60 * int(startTime[:2]) + int(startTime[3:])
t1 = 60 * int(finishTime[:2]) + int(finishTime[3:])
if t1 < t0:
# 此时 finishTime 为第二天
t1 += 1440
# 第一个小于等于 finishTime 的完整对局的结束时间
t1 = t1 // 15 * 15
return max(0, (t1 - t0)) // 15
1904. 你完成的完整对局数
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/the-number-of-full-rounds-you-have-played/
前置知识
题目描述
给你两个字符串 startTime 和 finishTime ,均符合 "HH:MM" 格式,分别表示你 进入 和 退出 游戏的确切时间,请计算在整个游戏会话期间,你完成的 完整对局的对局数 。
例如,如果 startTime = "05:20" 且 finishTime = "05:59" ,这意味着你仅仅完成从 05:30 到 05:45 这一个完整对局。而你没有完成从 05:15 到 05:30 的完整对局,因为你是在对局开始后进入的游戏;同时,你也没有完成从 05:45 到 06:00 的完整对局,因为你是在对局结束前退出的游戏。
如果 finishTime 早于 startTime ,这表示你玩了个通宵(也就是从 startTime 到午夜,再从午夜到 finishTime)。
假设你是从 startTime 进入游戏,并在 finishTime 退出游戏,请计算并返回你完成的 完整对局的对局数 。
示例 1:
输入:startTime = "12:01", finishTime = "12:44" 输出:1 解释:你完成了从 12:15 到 12:30 的一个完整对局。 你没有完成从 12:00 到 12:15 的完整对局,因为你是在对局开始后的 12:01 进入的游戏。 你没有完成从 12:30 到 12:45 的完整对局,因为你是在对局结束前的 12:44 退出的游戏。
示例 2:
输入:startTime = "20:00", finishTime = "06:00" 输出:40 解释:你完成了从 20:00 到 00:00 的 16 个完整的对局,以及从 00:00 到 06:00 的 24 个完整的对局。 16 + 24 = 40
示例 3:
输入:startTime = "00:00", finishTime = "23:59" 输出:95 解释:除最后一个小时你只完成了 3 个完整对局外,其余每个小时均完成了 4 场完整对局。
提示:
startTime 和 finishTime 的格式为 HH:MM 00 <= HH <= 23 00 <= MM <= 59 startTime 和 finishTime 不相等