mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
cs: add «539. Minimum Time Difference»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
967ca0f1a2
commit
11f539ddd6
1 changed files with 42 additions and 0 deletions
42
cs/minimum-time-difference.cs
Normal file
42
cs/minimum-time-difference.cs
Normal file
|
@ -0,0 +1,42 @@
|
||||||
|
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()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue