LeetCode/cs/minimum-time-difference.cs

43 lines
1.3 KiB
C#
Raw Permalink Normal View History

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()
);
}
}