53 lines
1.4 KiB
C#
53 lines
1.4 KiB
C#
|
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];
|
||
|
}
|
||
|
}
|