Алгоритм: вставка и объединение интервалов 57. Вставка интервала

57. Вставить интервал

Вам дан массив непересекающихся интервалов intervals, где intervals[i] = [starti, endi] представляют начало и конец i-го интервала, а интервалы отсортированы в порядке возрастания по starti. Вам также дан интервал newInterval = [start, end], который представляет собой начало и конец другого интервала.
Вставьте newInterval в интервалы таким образом, чтобы интервалы по-прежнему сортировались в порядке возрастания по началу, а интервалы по-прежнему не имели перекрывающихся интервалов (при необходимости объедините перекрывающиеся интервалы).
Интервалы возврата после вставки.

Пример 1:

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]

Пример 2:

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].

Ограничения:

  • 0 <= интервалы.длина <= 104
  • интервалы[i].length == 2
  • 0 <= начало <= конец <= 105
  • интервалы сортируются по началу в порядке возрастания.
  • новыйИнтервал.длина == 2
  • 0 <= начало <= конец <= 105

Бинарный поиск находит положение головы, вставляет новый интервал в соответствующий вопрос, а затем снова проходит объединенный интервал.

class Solution:
    def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
        res = []
        i = 0
        n = len(intervals)
        # while i < n and intervals[i][0] < newInterval[0]:
        #     i += 1
        i = self.binarySearch(intervals, newInterval[0])
        intervals.insert(i, newInterval)
        
        for item in intervals:
            if not res or item[0] > res[-1][1]:
                res.append(item)
            else:
                res[-1][1] = max(res[-1][1], item[1])

        return res
    
    def binarySearch(self, arr, target):
        l, r = 0, len(arr) - 1

        while l <= r:
            mid = l + (r - l) // 2
            mid_val = arr[mid][0]

            if mid_val == target:
                return mid
            elif mid_val < target:
                l = mid + 1
            else:
                r = mid - 1
        
        return l

Подробное объяснение бинарного поиска

Двоичный поиск — это алгоритм поиска, используемый для нахождения положения определенного целевого значения в отсортированном массиве. Он работает путем многократного деления пространства поиска пополам до тех пор, пока целевое значение не будет найдено или определено как отсутствующее.
Вот реализация Python алгоритма бинарного поиска:

def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    
    while left <= right:
        mid = (left + right) // 2
        mid_val = arr[mid]

        if mid_val == target:
            return mid
        elif mid_val < target:
            left = mid + 1
        else:
            right = mid - 1

    return -1

В приведенном выше коде:

  •   The binary_search function takes two parameters: arr, the sorted list, and target, the value to search for.
    
  •   The left variable is initialized to 0, and the right variable is initialized to the index of the last element in the array.
    
  •   The while loop continues as long as left is less than or equal to right. This means there are still elements to search.
    
  •   In each iteration of the loop, the mid index is calculated as the middle index between left and right. The mid_val variable stores the value at the middle index.
    
  •   If the mid_val is equal to the target, the function returns the index mid, indicating that the target has been found.
    
  •   If the mid_val is less than the target, it means the target must be in the right half of the remaining search space. So, the left pointer is moved to mid + 1.
    
  •   If the mid_val is greater than the target, it means the target must be in the left half of the remaining search space. So, the right pointer is moved to mid - 1.
    
  •   The loop continues to divide the search space in half until the target is found or until left becomes greater than right, indicating that the target is not present in the array.
    
  •   If the target is not found, the function returns -1.
    

Важно отметить, что алгоритм бинарного поиска работает только с отсортированными массивами. Если массив не отсортирован, результаты будут неверными.

рекомендация

отblog.csdn.net/zgpeace/article/details/131820640
рекомендация