Algorithm Notes
  • Introduction
  • 开头
    • Longest Palindrome 最长回文串
    • Valid Palindrome 有效回文串
    • Valid Palindrome II
    • Implement strStr()
    • Longest Palindromic Substring 最长回文子串
    • Longest Palindromic Subsequence 最长的回文序列
  • Binary Search & O(logN)
    • Total Occurrence of Target 目标出现总和
    • Closest Number in Sorted Array 排序数组中最接近元素
    • Search a 2D Matrix II 搜索二维矩阵 II
    • Smallest Rectangle Enclosing Black Pixels 包裹黑色像素点的最小矩形
    • Search in a Big Sorted Array 在大数组中查找
    • Maximum Number in Mountain Sequence 山脉序列中的最大值
    • Find Minimum in Rotated Sorted Array 寻找旋转排序数组中的最小值
    • Find Minimum in Rotated Sorted Array II 寻找旋转排序数组中的最小值 II
    • Search in Rotated Sorted Array 搜索旋转排序数组
    • Search in Rotated Sorted Array II 搜索旋转排序数组 II
    • Recover Rotated Sorted Array 恢复旋转排序数组
    • Copy Books 及其几道变形题
  • 数值类
    • Count Primes, Kth Prime Number
    • Prime Factorization 分解质因数
    • Divide Two Integers
    • Greatest Common Divisor 最大公约数(辗转相除法)
    • Pow(x, n) 快速幂
    • 幂数取余
  • Binary Tree
    • Closest Binary Search Tree Value
    • Binary Tree Inorder Traversal 二叉树的中序遍历
    • Binary Tree Preorder Traversal 二叉树的前序遍历
    • Binary Tree Postorder Traversal 二叉树的后序遍历
    • Binary Search Tree Iterator 二叉查找树迭代器
    • Inorder Predecessor in BST
    • Inorder Successor in BST
    • Minimum Subtree 最小子树
    • Binary Tree Paths 二叉树的所有路径
    • Flatten Binary Tree to Linked List 将二叉树拆成链表
    • Balanced Binary Tree 平衡二叉树
    • Kth Smallest Element in BST
    • Lowest Common Ancestor of a Binary Search Tree
    • Lowest Common Ancestor II 最近公共祖先 II
    • Lowest Common Ancestor 最近公共祖先
    • Lowest Common Ancestor III 最近公共祖先 III
    • Maximum Depth of Binary Tree 二叉树的最大深度
    • Minimum Depth of Binary Tree 二叉树的最小深度
    • Path Sum
    • Path Sum II / Binary Tree Path Sum 二叉树的路径和
    • Path Sum III / Binary Tree Path Sum II
    • Path Sum IV / Binary Tree Path Sum IV
    • Binary Tree Path Sum III
    • Closest Binary Search Tree Value II
  • Linked List
    • Reverse Linked List
    • Reverse Linked List II
    • Add Two Numbers
    • Add Two Numbers II
  • Two Pointers 双指针/滑动窗口/Two Sum
    • Middle of linked list 链表的中点
    • Move Zeroes 移动零
    • Window Sum 滑动窗口内数的和
    • Remove Duplicate Numbers in Array 去除重复元素
    • Sort Colors 颜色分类
    • Two Sum 两数之和
    • Two Sum II - Input array is sorted 两数和-输入已排序的数组
    • Two Sum III - Data structure design 两数之和-数据结构设计
    • Two Sum - Greater than target
    • Two Sum - Closest to target
    • Two Sum - Unique pairs
    • 3Sum 三数之和
    • 3Sum Closest 最接近的三数之和
    • 3Sum Smaller
    • 3sum II 三数之和 II
    • Permutation in String
    • Same Number
    • Minimum Size Subarray Sum
    • Longest Substring Without Repeating Characters
    • Longest Substring with At Most K Distinct Characters
  • Breadth First Search 宽度优先搜索
    • Number of Islands 岛屿的个数
    • Surrounded Regions 被围绕的区域
    • Topological Sorting 拓扑排序
    • Course Schedule 课程表
    • Course Schedule II 课程表 II
    • Sequence Reconstruction 序列重构
    • Clone Graph 克隆图
    • Word Ladder 单词接龙
    • Graph Valid Tree 图是否是树
    • Binary Tree Zigzag Level Order Traversal 二叉树的锯齿形层次遍历
    • 缺了1号刷的几个题
    • Binary Tree Level Order Traversal II 二叉树的层次遍历 II
    • Sliding Puzzle II 滑动拼图II
    • Build Post Office II 邮局的建立 II
    • Knight Shortest Path 骑士的最短路线
    • Police Distance
    • Directed Graph Loop
  • DFS - Combination Based
    • Split String 分割字符串
    • Find the Missing Number II 寻找丢失的数 II
    • Palindrome Partitioning 分割回文串
    • Combinations 组合
    • Subsets 子集
    • Subsets II 带重复元素的子集
    • Combination Sum
    • Combination Sum II
    • Combination Sum III
    • Combination Sum IV
    • Word Break II 单词拆分II
  • Greedy 贪心
    • 几个必须“背诵”的贪心算法题
    • Missing Number / Find the Missing Number
    • Jump Game
    • Jump Game II
    • Queue Reconstruction by Height
  • Bit Manipulation 位运算
    • Missing Number / Find the Missing Number
    • Update Bits
    • A + B Problem
    • O(1) Check Power of 2
    • Count 1 in Binary
    • Flip Bits
    • Subsets
    • Single Number
    • Single Number II
    • Single Number III
  • DFS - Permutation Based and Graph Based
    • Permutation Index 排列序号
    • Permutation Index II 排列序号II
    • Next Permutation 下一个排列
    • previous permutation 上一个排列
    • Permutations 全排列
    • Permutations II 全排列 II
    • String Permutation I & II
    • Next Closest Time
    • Letter Combinations of a Phone Number
    • Word Squares
    • Word Pattern II
    • Word Search 单词搜索
    • Word Search II 单词搜索 II
    • Word Ladder II 单词接龙 II
  • Dynamic Programming 动态规划
    • Word Break 单词拆分 I
    • Word Break III 单词拆分 III
    • Ones and Zeroes
    • Largest Divisible Subset
    • Perfect Squares
    • Stone Game
    • Unique Paths
    • Unique Paths II
    • Unique Paths III
    • Jump Game
    • Coin Change
    • Coin Change 2
    • Maximum Product Subarray
    • Minimum Path Sum
    • Decode Ways
    • Bomb Enemy
    • Paint House
    • Paint House II
    • Counting Bits
    • Longest Increasing Subsequence
    • Russian Doll Envelopes
    • Digital Flip
    • Best Time to Buy and Sell Stock III
    • Best Time to Buy and Sell Stock IV
    • Copy Books
    • Copy Books II
    • Coins in a Line
    • Coins in a Line II
    • Coins in a Line III
    • Burst Balloons
    • Scramble String
    • Longest Common Subsequence
    • Interleaving String
    • Distinct Subsequences
    • Edit Distance
    • K Edit Distance
    • Wildcard Matching
    • Regular Expression Matching
    • Rogue Knight Sven
    • Decode Ways II
    • Maximal Square
    • Predict the Winner
    • Merge stone 石子合并 系列
  • Knapsack / Backpack 背包问题
    • Knapsack / Rucksack / Backpack 背包问题
    • Backpack II 背包 II
    • Backpack III 背包 III
    • Backpack IV 背包 IV
    • Backpack V 背包 V
    • Combination Sum IV 别名 背包 VI
    • Backpack VII 背包 VII
    • Backpack VIII 背包 VIII
    • Backpack IX 背包 IX
    • Backpack X 背包X
    • k Sum
  • Stack Queue Hash Heap - Data Structure
    • Word Pattern
    • Isomorphic Strings / Strings Homomorphism 字符同构
    • Moving Average from Data Stream
    • Implement Stack
    • Hash Function 哈希函数
    • Implement Stack using Queues / Implement Stack by Two Queues
    • First Unique Character in a String
    • First Unique Number in a Stream I & II
    • Insert Delete GetRandom O(1)
    • Insert Delete GetRandom O(1) - Duplicates allowed
    • Kth Largest Element II 第K大的元素 II
    • K Closest Points
    • Top k Largest Numbers 前K大数
    • Merge k Sorted Lists
    • Ugly Number II
    • Implement Queue using Stacks
    • LRU Cache
    • High Five 优秀成绩
    • Flatten 2D Vector 摊平二维向量
    • Top k Largest Numbers II 前K大数 II
    • Load Balancer 负载均衡器
    • Rehashing 重哈希
    • Heapify 堆化
    • Longest Consecutive Sequence 最长连续序列
    • Kth Largest in N Arrays
    • Kth Smallest Element in a Sorted Matrix
    • Kth Smallest Sum In Two Sorted Arrays
    • Find K Pairs with Smallest Sums
    • Find K-th Smallest Pair Distance
    • Bulls and Cows
    • Find Median from Data Stream
    • Sliding Window Median
  • Array Matrix Interval Binary-indexed-tree
    • Merge Intervals
    • Merge Two Sorted Interval Lists
    • Merge K Sorted Interval Lists
    • Merge Sorted Array
    • Merge Two Sorted Arrays
    • Merge K Sorted Arrays
    • Intersection of Two Arrays 两数组的交
    • Intersection of Two Arrays II
    • --- Sub-Array, Sub-Matrix ---
    • Subarray Sum
    • Maximum Subarray
    • Range Sum Query - Immutable
    • Range Sum Query 2D - Immutable
    • Range Sum Query - Mutable
    • Range Sum Query 2D - Mutable
    • Submatrix Sum
    • Maximum Submatrix
    • Median of two Sorted Arrays
    • Median of K Sorted Arrays
    • Sparse Matrix Multiplication
    • Best Time to Buy and Sell Stock
    • Best Time to Buy and Sell Stock II
  • Segment Tree
    • Basic Operations: Build, Modify and Query
    • Interval Sum 区间求和
    • Interval Sum II 区间求和 II
    • Interval Minimum Number
    • Count of Smaller Number
    • Count of Smaller Number before itself
    • Count of Smaller Numbers After Self
  • Trie 字典树
    • Implement Trie (Prefix Tree)
    • Map Sum Pairs
    • Replace Words
    • Add and Search Word - Data structure design
    • Maximum XOR of Two Numbers in an Array
    • Word Search II
  • Union Find
    • Maximum Association Set
    • Connecting Graph
    • Connecting Graph II
    • Connecting Graph III
    • Number of Islands II
    • Redundant Connection
  • Basic Calculator (Series 1 ~ 4)
    • Basic Calculator
    • Basic Calculator II
    • Basic Calculator III
    • Basic Calculator IV
  • 灌水类
    • Trapping Rain Water
    • Trapping Rain Water II
    • Container With Most Water
    • Swim in Rising Water
  • 其它类
    • Wiggle Sort 摆动排序
    • Wiggle Sort II 摆动排序 II
    • Build Post Office 邮局的建立
    • Minimum Cycle Section
    • Transform to Chessboard
    • Longest Continuous Increasing Subsequence
  • 经典算法和数据结构
    • Quick Sort, Quick Select, Partition
      • Partition Array 数组划分
      • Sort Colors II 排颜色 II
      • Quick Select · Kth Largest Element 第K大元素
      • Quick Sort
    • 最短路(Dijkstra)算法
    • Bucket Sort 桶排序
    • Rainbow Sort
    • Cantor Expansion 康托展开
    • 图最长路径
    • Prefix Sum 前缀和
    • Binary Indexed Tree or Fenwick Tree
    • Segment Tree 线段树
    • Trie or Prefix Tree
  • 较难的算法
    • Manacher's Algorithm
    • Rabin Karp
    • Pollard Rho快速因数分解
    • A* 算法
  • 其他知识点
    • 还未解的题
    • 面试中常见算法的时间复杂度
    • 复杂度分析
    • 基本文件读写
    • Dynamic type languages versus static type languages
    • B+ Tree, R Tree, Bloom Filter
    • 内存中堆栈的理解
    • 面试中的系统设计部分怎么准备
    • 负数的二进制表示
    • 求最大公约数
  • Python知识点
    • Call by object reference
    • Collections
    • Enumerate
    • 二维数组取列
    • Generators Yield
    • Hash Table
    • Heap
    • Python 2 和 3 的主要区别
    • Queue Stack
    • range 和 xrange
    • Reverse a string list
    • Set
    • String manipulation 字符串处理
    • List Comprehension (Sets, Dicts)
    • 一些 Python 教程的网站
    • 2D Array Declaration
    • Lambda, filter, reduce and map
    • Nested list 转 nested tuple
    • Python data structure time complexity
    • Comparison magic methods
    • bisect — Array bisection algorithm
    • 打印一个数的二进制
    • Python 位运算位数限制
    • classmethod and staticmethod
    • 全局变量和局部变量 Global and Local Variables
  • Java知识点
    • LinkedHashMap
  • C++知识点
    • Comparator
  • System Design
    • Design Twitter
    • Consistent Hashing
  • LeetCode Weekly Contest 81
    • Shortest Distance to a Character
    • Card Flipping Game
    • Short Encoding of Words
    • Binary Trees With Factors
  • LintCode Weekly Mock Interview 15 (For Amazon Onsite)
    • Log Sorting
    • Minimum String Array Coverage
    • Find Substring
    • The Longest Scene
    • Most Frequent Subtree Sum
  • LintCode Quarter Contest 2018-04-27
    • Perfect Squares
    • House Robber
    • Cable Car Ride
    • Lucky Number Eight
    • High Capacity Backpack
    • Subtree Count
    • Segment Stones Merge
    • Maximum Line Coverage
  • LeetCode Weekly Contest 82
    • Goat Latin
    • Friends Of Appropriate Ages
    • Most Profit Assigning Work
    • Making A Large Island
  • LintCode Weekly Mock Interview 16 (For Facebook Onsite)
    • K Decimal Addition
    • Digital Coverage
    • Set Union
    • The Barycentre Of The Trees
    • Integer to English Words
  • LeetCode Weekly Contest 83
    • Positions of Large Groups
    • Masking Personal Information
    • Consecutive Numbers Sum
    • Unique Letter String
  • LintCode Weekly Mock Interview 17 (For Google Onsite)
    • Twitch Words
    • Recommend Friends
    • Fermat Point Of Graphs
    • Take Coins
    • Number of Atoms
  • LeetCode Weekly Contest 84
    • Flipping an Image
    • Find And Replace in String
    • Image Overlap
    • Sum of Distances in Tree
  • LintCode Weekly Mock Interview 18
    • Matrix Water Injection
    • Maximum Product Path
    • Matrix Finding Number
    • Gas Station II
    • Basic Calculator III
  • LeetCode Weekly Contest 85
  • LintCode Weekly Mock Interview 19 (For Twitter Onsite)
    • Residual Product
    • The Previous Number
    • Eat The Beans
    • Tree
    • Find the Difference
  • LeetCode Weekly Contest 86
    • Magic Squares In Grid
    • Keys and Rooms
    • Split Array into Fibonacci Sequence
    • Guess the Word
  • LintCode Weekly 20 (For Hulu Onsite)
    • Weighing Problem
    • Print Organization Chart
    • Maximum Slope Straight Line
    • Construction Queue
  • LeetCode Weekly 87
    • Backspace String Compare
    • Longest Mountain in Array
    • Hand of Straights
    • Shortest Path Visiting All Nodes
  • LintCode Weekly 22
  • LeetCode Weekly 89
  • LintCode Weekly 23
  • LeetCode Weekly 90
    • Buddy Strings
    • Score of Parentheses
    • Mirror Reflection
    • Minimum Cost to Hire K Workers
  • LintCode Weekly 25
    • Time Intersection
    • Leftmost One
    • Maximum Subarray VI
  • LeetCode Weekly 92
    • Transpose Matrix
    • Smallest Subtree with all the Deepest Nodes
  • LintCode Weekly 26
    • Set Operation
    • Predict the Winner / The Game Of Take Numbers
    • Longest Path On The Tree
    • Ask For Cooling Time
  • LeetCode Weekly 93
    • Binary Gap
    • Reordered Power of 2
    • Advantage Shuffle
    • Minimum Number of Refueling Stops
  • LintCode Weekly 27
    • Twins Strings
    • Shortest Phrase
    • Find The Sum Of The Array
  • LeetCode Weekly 94
  • LintCode Weekly 28
    • Function Runtime
    • Judging Triangle
    • Cartesian Product
    • Longest Sequence
  • LeetCode Weekly 95
    • Middle of the Linked List
    • Stone Game
    • Nth Magical Number
    • Profitable Schemes
  • LintCode Weekly 29
    • Coin Problem
    • Climbing Stairs III
    • Parking Problem
    • Order Problem
  • LeetCode Weekly 96
    • Projection Area of 3D Shapes
    • Boats to Save People
    • Decoded String at Index
    • Reachable Nodes In Subdivided Graph
  • LintCode Weekly 30
    • Take the element and query the sum
    • MinimumString
    • Array Maximum Value
  • LeetCode Weekly 97
    • Uncommon Words from Two Sentences
    • Spiral Matrix III
    • Possible Bipartition
  • LintCode Weekly 31
  • LeetCode Weekly 98
  • LintCode Weekly 32
    • Spring Tour
    • Legal String
    • Asking For The Longest 01 Substring
    • Music Playlist
  • LeetCode Weekly 99
    • Surface Area of 3D Shapes
    • Groups of Special-Equivalent Strings
    • All Possible Full Binary Trees
    • Maximum Frequency Stack
  • LeetCode Weekly 104
    • X of a Kind in a Deck of Cards
    • Partition Array into Disjoint Intervals
    • Word Subsets
    • Cat and Mouse
  • LeetCode Weekly 120
    • Squares of a Sorted Array
    • Longest Turbulent Subarray
    • Distribute Coins in Binary Tree
    • Unique Paths III
  • LeetCode Weekly 130
    • Binary Prefix Divisible By 5
    • Convert to Base -2
Powered by GitBook
On this page

Was this helpful?

  1. Array Matrix Interval Binary-indexed-tree

Merge Two Sorted Interval Lists

LintCode 839

Merge two sorted (ascending) lists of interval and return it as a new sorted list. The new sorted list should be made by splicing together the intervals of the two lists and sorted in ascending order.

Notice

  • The intervals in the given list do not overlap.

  • The intervals in different lists may overlap.

Example

Given list1 =[(1,2),(3,4)]and list2 =[(2,3),(5,6)], return[(1,4),(5,6)].

合并 interval 的思路和上一题一样。合并2个 interval lists 可以套用合并2个sorted array的方法,两个list打擂台。

    def mergeTwoInterval(self, list1, list2):
        if not list1 or not list2:
            return list1 + list2

        lo = hi = min(list1[0].start, list2[0].start)
        i, j, result = 0, 0, []
        while i < len(list1) or j < len(list2):
            if i == len(list1):
                interval = list2[j]
                j += 1
            elif j == len(list2):
                interval = list1[i]
                i += 1                
            elif list1[i].start < list2[j].start:
                interval = list1[i]
                i += 1
            else:
                interval = list2[j]
                j += 1

            if interval.start > hi:
                result.append(Interval(lo, hi))
                lo, hi = interval.start, interval.end
            else:
                hi = max(hi, interval.end)

        result.append(Interval(lo, hi))

        return result[: ]

九章的思路

用一个 last 来记录最后一个还没有被放到 merge results 里的 Interval,用于和新加入的 interval 比较看看能不能合并到一起。

时间复杂度O(n + m)O(n+m)

public class Solution {
    /**
     * @param list1: one of the given list
     * @param list2: another list
     * @return: the new sorted list of interval
     */
    public List<Interval> mergeTwoInterval(List<Interval> list1, List<Interval> list2) {
        List<Interval> results = new ArrayList<>();
        if (list1 == null || list2 == null) {
            return results;
        }
        
        Interval last = null, curt = null;
        int i = 0, j = 0;
        while (i < list1.size() && j < list2.size()) {
            if (list1.get(i).start < list2.get(j).start) {
                curt = list1.get(i);
                i++;
            } else {
                curt = list2.get(j);
                j++;
            }
            
            last = merge(results, last, curt);
        }
        
        while (i < list1.size()) {
            last = merge(results, last, list1.get(i));
            i++;
        }
        
        while (j < list2.size()) {
            last = merge(results, last, list2.get(j));
            j++;
        }
        
        if (last != null) {
            results.add(last);
        }
        return results;
    }
    
    private Interval merge(List<Interval> results, Interval last, Interval curt) {
        if (last == null) {
            return curt;
        }
        
        if (curt.start > last.end) {
            results.add(last);
            return curt;
        }
        
        last.end = Math.max(last.end, curt.end);
        return last;
    }
}
PreviousMerge IntervalsNextMerge K Sorted Interval Lists

Last updated 5 years ago

Was this helpful?