TGViewer
C# | LeetCode C# | LeetCode @easy_c_sharp_task · 3.17K subscribers
Post #1408 347
Задача: 57. Insert Interval
Сложность: medium

Дан массив intervals, содержащий непересекающиеся интервалы, отсортированные по start. Дано newInterval = [start, end].

Нужно вставить newInterval так, чтобы intervals оставался отсортированным и не имел пересекающихся интервалов.

Пример:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]  
Output: [[1,5],[6,9]]


👨‍💻 Алгоритм:

1⃣Добавить в результат все интервалы, которые переходят к новому интервалу и не пересекаются с ними.

2⃣Объединить все пересекающиеся интервалы с newInterval в один.

3⃣Добавить функциональные интервалы без изменений.

😎 Решение:
public class Solution {
public int[][] Insert(int[][] intervals, int[] newInterval) {
int n = intervals.Length, i = 0;
List<int[]> res = new List<int[]>();

while (i < n && intervals[i][1] < newInterval[0]) {
res.Add(intervals[i]);
i++;
}

while (i < n && newInterval[1] >= intervals[i][0]) {
newInterval[0] = Math.Min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.Max(newInterval[1], intervals[i][1]);
i++;
}

res.Add(newInterval);

while (i < n) {
res.Add(intervals[i]);
i++;
}

return res.ToArray();
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_c_sharp_task
  1. Oct 16, 2026Задача: 205. Isomorphic Strings Сложность: easy Даны две строки s и t, определите, являютс…
  2. Oct 16, 2026Задача: 1416. Restore The Array Сложность: hard Программа должна была напечатать массив це…
  3. Oct 15, 2026Задача: 217. Contains Duplicate Сложность: easy Дан массив целых чисел nums. Верните true,…
  4. Oct 15, 2026Задача: 759. Employee Free Time Сложность: hard Нам дан список schedule of employees, кото…
  5. Oct 14, 2026Задача: 583. Delete Operation for Two Strings Сложность: medium Даны две строки word1 и wo…
  6. Oct 14, 2026Задача: 1252. Cells with Odd Values in a Matrix Сложность: easy Имеется матрица m x n, кот…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →