算法: 插入和合并间隔57. Insert Interval

57. Insert Interval

You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval.
Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return intervals after the insertion.

Example 1:

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

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

Constraints:

  • 0 <= intervals.length <= 104
  • intervals[i].length == 2
  • 0 <= starti <= endi <= 105
  • intervals is sorted by starti in ascending order.
  • newInterval.length == 2
  • 0 <= start <= end <= 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

二分查找详解

Binary search is a search algorithm used to find the position of a specific target value within a sorted array. It works by repeatedly dividing the search space in half until the target value is found or determined to be not present.
Here’s a Python implementation of the binary search algorithm:

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

In the code above:

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

It’s important to note that the binary search algorithm works only on sorted arrays. If the array is not sorted, the results will be incorrect.

猜你喜欢

转载自blog.csdn.net/zgpeace/article/details/131820640