LeetCode-Notes
  • Introduction
  • Records of Practice
  • 关于Github 不支持密码问题
  • 面试题
    • 搜索广告
    • 多模态大模型
    • 刷题记录
  • 算法代码实现
  • Python
    • Python 笔记
  • Spark
    • PySpark
    • Spark Issues
    • Spark调优笔记
  • FeatureEngineering
    • Feature Cleaning
    • Feature Selection
    • Feature Transformation
    • Feature Crossing
  • Recommendation Algorithm
    • Recall-and-PreRank
      • Non-Negative Matrix Fatorization(NMF)
      • Fatorization Machine(FM)
      • User-base/Item-base实现
      • 多路召回实现
    • Ranking
      • NeuralFM
      • DeepFM
      • Deep&Cross network (DCN)
    • DeepLearning-Basic
      • Attention
      • Dropout
      • Batch Norm
  • Machine Learning
    • XGBoost
    • Cross Entropy Loss
    • Other models
  • Graph Neural Network
    • GNN-1-Basic
  • Big Data
    • Reservoir Sampling
  • SQL
    • SQL and PySpark functions
    • Query Film Infomation
    • Create, Insert and Alter Actor Table
    • Manage Employment Data
    • Manage Employment Data -2
  • DataStructure
    • Searching
      • Find power
      • 2 Sum All Pair II
      • Two Sum
      • Search in Rotate Array
      • Search In Shifted Sorted Array II
      • Search in 2D array
      • Three Sum with duplicated values
      • Median of Two Sorted Arrays
    • Array
      • Longest Consecutive Subarray
      • Merge Two Array in-place
      • Trapping water
      • Rotate matrix
    • Sorting
      • Merge intervals
      • 排序
      • 最小的k个数
      • Find TopK largest- QuickSelect快速选择 method
      • MergeSort Linkedlist
      • 第K大元素
    • LinkedList
      • Reverse LinkedList I
      • Reverse K-group linked list
      • Detect Start of Cycle
      • HasCycle
      • DetectCycle II
      • 链表的共同节点
      • 链表中倒数第k个节点
      • 删除链表倒数第k个节点
      • 合并两个链表
      • 在排序数组中查找元素的第一个和最后一个位置
      • 删除链表里面重复的元素-1
    • Tree
      • Find Tree height (general iteration method)
      • Check BST and Check CompleteTree
      • ZigZag Order traversal
      • Binary Tree diameter I
      • Maximum Path Sum Binary Tree
      • Maximum Path Sum Binary Tree II
      • Binary Tree Path Sum To Target III
      • Tree diameter 树的直径II
      • Tree ReConstruction
      • Check if B is Subtree of A
      • The Kth smallest in Binary Search Tree
      • 打印Tree的右视图
      • 二叉搜索树的后序遍历序列
      • 重建二叉树
      • 判断二叉树是否对称
      • Path Sum to Target in Binary Tree
      • Tree-PreOrder-InOrder-PostOrder
    • Heap&Queue
      • Top-K smallest
      • 滑动窗口最大值
      • Find the K-Largest
    • 合并k个已排序的链表
    • String
      • Reverse String
      • 最长不含重复字符的子字符串
      • 最长回文串
      • 最长回文子序列-DP
    • DFS/BFS
      • Number of island
      • Number of Provinces
      • All Permutations of Subsets without duplication
      • All Permutations of Subsets with duplication
      • Combinations Of Coins
      • All Subset I (without fixing size of subset, without order, without duplication)
      • All Subset of K size without duplication II
      • All Subset of K size III (with duplication without considering order)
      • All Permutation II (with duplication and consider order)
      • Factor Combination-质数分解
    • DynamicProgramming
      • DP-解题过程
      • Find Continuous Sequence Sum to Target
      • 1800. Maximum Ascending Subarray Sum
      • NC91 最长上升子序列
      • 查找string的编码方式个数
      • Maximum Product
      • Longest Common Substring
      • Longest Common Substring-II
      • minEditCost
      • Backpack I
      • Array Hopper I
      • Minimum distance between strings
      • 最大正方形
  • Big Data Algorithms
    • Big Data Processing Algorithms
      • Reservior Sampling
      • Shuffle
      • MapReduce
      • Bloom Filter
      • BitMap
      • Heap For Big Data
Powered by GitBook
On this page
  • 1. Links
  • 2.题目描述
  • 输入
  • 返回值
  • 3.思路
  • 4. Code

Was this helpful?

  1. DataStructure
  2. Sorting

Merge intervals

难度: Medium, 公司: 字节 研发 facebook

PreviousSortingNext排序

Last updated 3 years ago

Was this helpful?

1. Links

牛客:

2.题目描述

给出一组区间,请合并所有重叠的区间。请保证合并后的区间按区间起点升序排列。示例1

输入

复制

[[10,30],[20,60],[80,100],[150,180]]

返回值

复制

[[10,60],[80,100],[150,180]]

3.思路

  1. 先把intervals按照start 进行排序

  2. two points method: slow pt 指向要返回的list的最后一个interval, fast pt用于遍历查找下一个interval

  3. 对比slowpt interval和fast pt的interval

    1. case 1: if slow interval.end > fast.interval. end ->continue

    2. case 2: if slow interval.end > fast. interval .start and slow interval end < fast interval.end -> merge intervals by updating slow.interval end = fast.interval.end

    3. case 3: if slow interval end < fast interval.start -> slow += 1, copy fast interval to slow

    4. move fast forward by 1

  4. Time: O(nlogn) for sorting +O(n) for merging. Space: O(1)

4. Code

# class Interval:
#     def __init__(self, a=0, b=0):
#         self.start = a
#         self.end = b

#
# 
# @param intervals Interval类一维数组 
# @return Interval类一维数组
#
class Solution:
    def merge(self , intervals ):
        # write code here
        # question: merge two regions if two regions overlap, input: list of interval
        #  output: list of interval after merge ascending 
        # idea: 
        # 1.  sort list based on interval start
        # 2. case 1: the end of the last interval in res > the start of the first interval in intervals
        #    case 2: the end of the last interval in res > the end of the first interval in intervals
        # Time: O(nlogn) sorting, O(n) merging -> O(nlogn +n), O(n) for popping
        #    s O(n^2)
        #base case:  intervals length <2: return intervals
        # test case: 
        #[[10,30],[20,60],[80,100],[150,180]]
#         if not intervals or len(intervals)<=1:
#             return intervals
        
#         intervals.sort(key = lambda x : x.start)
#         inv = intervals.pop(0)
#         res = [Interval(inv.start, inv.end)]
#         while intervals:
#             if intervals[0].start <= res[-1].end and intervals[0].end <= res[-1].end:
#                 intervals.pop(0)
#             elif intervals[0].start <= res[-1].end and intervals[0].end > res[-1].end:
#                 res[-1].end = intervals[0].end
#                 intervals.pop(0)
#             else:
#                 inv = intervals.pop(0)
#                 res.append(Interval(inv.start, inv.end))
#         return res
    
        #Method 2: use pointer rather than popping of element
        #    
        #
        #
        if not intervals or len(intervals)<=1:
            return intervals
        # O(nlogn)
        intervals.sort(key = lambda x : x.start)
        slow, fast = 0,0
        #O(n)
        while fast< len(intervals):
            if intervals[slow].end > intervals[fast].end:
                fast += 1
            elif intervals[slow].end <= intervals[fast].end and intervals[slow].end >= intervals[fast].start:
                # merge if overlap
                intervals[slow].end  = intervals[fast].end
                fast += 1
            else:
                slow += 1
                intervals[slow] = intervals[fast]
                fast += 1
        return intervals[:slow+1]
                
                
            
        
        
    
class Solution:
    # array 二维列表
    def Find(self, target, array):
        #
        #input: target int, 2D array,  output: boolean 
        # idea: binary search
        # search from upper left corner
        # since element < cur on the left, >cur on the bottom, so
        # check current element:
        #  case 1: if current clement < target ->search bottom
        # case 2: if current elemtn > target -> search left side
        if not array or not array[0] or target == None:
            return False
        
        r, c = 0, len(array[0])-1
        while c >=0 and r < len(array):
            if array[r][c] <target:
                r += 1
            elif array[r][c] >target:
                c -= 1
            else:
                return True
        return False
合并区间_牛客题霸_牛客网
Logo