cs: add «632. Smallest Range Covering Elements from K Lists»

URL:	https://leetcode.com/problems/smallest-range-covering-elements-from-k-lists/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-10-13 17:12:01 +02:00
parent 92c153c768
commit b50a4be64f
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,52 @@
public class Solution {
private struct Number : IComparable<Number> {
public int Value;
public int Index;
public Number(int value, int index) {
Value = value;
Index = index;
}
public int CompareTo(Number other) => Value.CompareTo(other.Value);
}
public int[] SmallestRange(IList<IList<int>> nums) {
var merged = new List<Number>();
for (int i = 0; i < nums.Count; ++i) {
foreach (var num in nums[i]) {
merged.Add(new Number(num, i));
}
}
merged.Sort();
var freqs = new Dictionary<int, int>();
int left = 0, count = 0;
int start = 0, end = int.MaxValue;
for (int right = 0; right < merged.Count; ++right) {
var num = merged[right];
freqs[num.Index] = 1 + freqs.GetValueOrDefault(num.Index, 0);
if (freqs[num.Index] == 1) {
++count;
}
for (; count == nums.Count; ++left) {
var range = merged[right].Value - merged[left].Value;
if (range < end - start) {
start = merged[left].Value;
end = merged[right].Value;
}
--freqs[merged[left].Index];
if (freqs[merged[left].Index] == 0) {
--count;
}
}
}
return [start, end];
}
}