Algoritmo: Intervalo de inserción y fusión 57. Intervalo de inserción

57. Insertar intervalo

Se le proporciona una matriz de intervalos de intervalos que no se superponen donde los intervalos [i] = [starti, endi] representan el inicio y el final del i-ésimo intervalo y los intervalos se ordenan en orden ascendente por starti. También recibe un intervalo newInterval = [start, end] que representa el inicio y el final de otro intervalo.
Inserte newInterval en los intervalos de modo que los intervalos aún estén ordenados en orden ascendente por starti y los intervalos aún no tengan intervalos superpuestos (combine los intervalos superpuestos si es necesario).
Intervalos de retorno después de la inserción.

Ejemplo 1:

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

Ejemplo 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].

Restricciones:

  • 0 <= intervalos.longitud <= 104
  • intervalos[i].longitud == 2
  • 0 <= inicio <= fin <= 105
  • intervalos está ordenado por starti en orden ascendente.
  • nuevoIntervalo.longitud == 2
  • 0 <= inicio <= final <= 105

La búsqueda binaria encuentra la posición de la cabeza, inserta el nuevo intervalo en la pregunta correspondiente y luego atraviesa el intervalo fusionado nuevamente

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

Explicación detallada de la búsqueda binaria

La búsqueda binaria es un algoritmo de búsqueda que se utiliza para encontrar la posición de un valor objetivo específico dentro de una matriz ordenada. Funciona dividiendo repetidamente el espacio de búsqueda por la mitad hasta que se encuentra el valor objetivo o se determina que no está presente.
Aquí hay una implementación de Python del algoritmo de búsqueda binaria:

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

En el código de arriba:

  •   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.
    

Es importante tener en cuenta que el algoritmo de búsqueda binaria solo funciona en matrices ordenadas. Si la matriz no está ordenada, los resultados serán incorrectos.

Supongo que te gusta

Origin blog.csdn.net/zgpeace/article/details/131820640
Recomendado
Clasificación