アルゴリズム: 間隔の挿入とマージ 57. 間隔の挿入

57. インターバルの挿入

重複しない間隔の配列が与えられます。interval[i] = [starti, endi] は i 番目の間隔の開始と終了を表し、間隔は starti によって昇順に並べ替えられます。また、別の間隔の開始と終了を表す間隔 newInterval = [start, end] も指定されます。
newInterval を間隔に挿入して、間隔が starti によって昇順にソートされ、間隔に重複する間隔が存在しないようにします (必要に応じて重複する間隔をマージします)。
挿入後の間隔を返します。

例 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
  • 間隔は starti によって昇順に並べ替えられます。
  • newInterval.length == 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