mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-14 18:07:32 +01:00
43 lines
1.3 KiB
C#
43 lines
1.3 KiB
C#
|
using System.Collections.Immutable;
|
||
|
|
||
|
public class Solution {
|
||
|
private record Time(int hours, int minutes) {
|
||
|
public int Normalized { get => hours * 60 + minutes; }
|
||
|
|
||
|
public static int Distance(Time a, Time b) =>
|
||
|
Math.Abs(b.Normalized - a.Normalized);
|
||
|
|
||
|
public static bool TryParse(string? s, out Time time) {
|
||
|
if (s == null) {
|
||
|
goto TimeFailedTryParse;
|
||
|
}
|
||
|
|
||
|
var parts = s.Split(":");
|
||
|
if (parts.Length != 2) {
|
||
|
goto TimeFailedTryParse;
|
||
|
}
|
||
|
|
||
|
if (int.TryParse(parts[0], out var hours) && int.TryParse(parts[1], out var minutes)) {
|
||
|
time = new Time(hours, minutes);
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
TimeFailedTryParse:
|
||
|
time = new Time(0, 0);
|
||
|
return false;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public int FindMinDifference(IList<string> timePoints) {
|
||
|
var times = timePoints.Select(t => {
|
||
|
Time.TryParse(t, out var time);
|
||
|
return time;
|
||
|
}).OrderBy(time => time.Normalized).ToImmutableList();
|
||
|
|
||
|
return Math.Min(
|
||
|
24 * 60 - Time.Distance(times.Last(), times.First()),
|
||
|
times.Zip(times.Skip(1)).Select(pair => Time.Distance(pair.First, pair.Second)).Min()
|
||
|
);
|
||
|
}
|
||
|
}
|