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:
parent
92c153c768
commit
b50a4be64f
1 changed files with 52 additions and 0 deletions
52
cs/smallest-range-covering-elements-from-k-lists.cs
Normal file
52
cs/smallest-range-covering-elements-from-k-lists.cs
Normal 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];
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue