📖
LeetCode
  • Introduction
  • Array
    • Best Time To Buy And Sell Stock
      • 121.Best-Time-to-Buy-and-Sell-Stock
      • 122.Best-Time-to-Buy-and-Sell-Stock-II
      • 123.Best-Time-to-Buy-and-Sell-Stock-III
      • 188.Best-Time-to-Buy-and-Sell-Stock-IV
    • 1.Two-Sum
    • 1007.Minimum-Domino-Rotations-For-Equal-Row
    • 1031.Maximum-Sum-of-Two-Non-Overlapping-Subarrays
    • 1052.Grumpy-Bookstore-Owner
    • 11.Container-With-Most-Water
    • 1122.Relative-Sort-Array
    • 1163.Last-Substring-in-Lexicographical-Order
    • [118.Pascal's-Triangle](Array/118.Pascal's-Triangle.md)
    • 1181.Before-and-After-Puzzle
    • 1231.Divide-Chocolate
    • 1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers
    • 1304.Find-N-Unique-Integers-Sum-up-to-Zero
    • 134.Gas-Station
    • 135.Candy
    • 1352.Product-of-the-Last-K-Numbers
    • 136.Single-Number
    • 14.Longest-Common-Prefix
    • 1477.Find-Two-Non-overlapping-Sub-arrays-Each-With-Target-Sum
    • 15.3Sum
    • 152.Maximum-Product-Subarray
    • 16.3Sum-Closest
    • 163.Missing-Ranges
    • 169.Majority-Element
    • 18.4Sum
    • 189.Rotate-Array
    • 204.Count-Primes
    • 215.Kth-Largest-Element-in-an-Array
    • 217.Contains-Duplicate
    • 219.Contains-Duplicate-II
    • 220.Contains-Duplicate-III
    • 228.Summary-Ranges
    • 229.Majority-Element-II
    • 238.Product-of-Array-Except-Self
    • 239.Sliding-Window-Maximum
    • 243.Shortest-Word-Distance
    • 252.Meeting-Rooms
    • 266.Palindrome-Permutation
    • 268.Missing-Number
    • 273.Integer-to-English-Words
    • 279.Perfect-Squares
    • 283.Move-Zeroes
    • 287.Find-the-Duplicate-Number
    • 29.Divide-Two-Integers
    • 299.Bulls-and-Cows
    • 31.Next-Permutation
    • 325.Maximum-Size-Subarray-Sum-Equals-k
    • 334.Increasing-Triplet-Subsequence
    • 340.Longest-Substring-with-At-Most-K-Distinct-Characters
    • 347.Top-K-Frequent-Elements
    • 349.Intersection-of-Two-Arrays
    • 350.Intersection-of-Two-Arrays-II
    • 354.Russian-Doll-Envelopes
    • 367.Valid-Perfect-Square
    • 378.Kth-Smallest-Element-in-a-Sorted-Matrix
    • 38.Count-and-Say
    • 383.Ransom-Note
    • 387.First-Unique-Character-in-a-String
    • 4.Median-of-Two-Sorted-Arrays
    • 406.Queue-Reconstruction-by-Height
    • 410.Split-Array-Largest-Sum
    • 412.Fizz-Buzz
    • 419.Battleships-in-a-Board
    • 435.Non-overlapping-Intervals
    • 438.Find-All-Anagrams-in-a-String
    • 442.Find-All-Duplicates-in-an-Array
    • 457.Circular-Array-Loop
    • 509.Fibonacci-Number
    • 53.Maximum-Subarray
    • 539.Minimum-Time-Difference
    • 540.Single-Element-in-a-Sorted-Array
    • 56.Merge-Intervals
    • 560.Subarray-Sum-Equals-K
    • 57.Insert-Interval
    • 575.Distribute-Candies
    • 581.Shortest-Unsorted-Continuous-Subarray
    • 593.Valid-Square
    • 6.ZigZag-Conversion
    • 609.Find-Duplicate-File-in-System
    • 611.Valid-Triangle-Number
    • 621.Task-Scheduler
    • 628.Maximum-Product-of-Three-Numbers
    • 632.Smallest-Range-Covering-Elements-from-K-Lists
    • 659.Split-Array-into-Consecutive-Subsequences
    • 67.Add-Binary
    • 670.Maximum-Swap
    • 7.Reverse-Integer
    • 717.1-bit-and-2-bit-Characters
    • 722.Remove-Comments
    • 724.Find-Pivot-Index
    • 763.Partition-Labels
    • 811.Subdomain-Visit-Count
    • 845.Longest-Mountain-in-Array
    • 846.Hand-of-Straights
    • 862.Shortest-Subarray-with-Sum-at-Least-K
    • 866.Prime-Palindrome
    • 881.Boats-to-Save-People
    • 937.Reorder-Data-in-Log-Files
    • 953.Verifying-an-Alien-Dictionary
    • 957.Prison-Cells-After-N-Days
    • 973.K-Closest-Points-to-Origin
    • 974.Subarray-Sums-Divisible-by-K
    • 995.Minimum-Number-of-K-Consecutive-Bit-Flips
    • Interleaving Positive And Negative Numbers
    • Maximum Subarray Difference
    • Maximum Subarray Ii
    • Merge Sorted Array Ii
    • Minimum Subarray
    • Partition Array
    • Recover Rotated Sorted Array
    • Subarray Sum Closest
    • Subarray Sum Zero
  • Basic Knowledge
    • Binary Tree
    • Bit Operation
    • Heapify
    • Java Syntax
    • Monotonous Stack
    • Trie Tree
  • Binary Search
    • 1011.Capacity-To-Ship-Packages-Within-D-Days
    • 1044.Longest-Duplicate-Substring
    • 1062.Longest-Repeating-Substring
    • 153.Find-Minimum-in-Rotated-Sorted-Array
    • 162.Find-Peak-Element
    • 278.First-Bad-Version
    • 33.Search-in-Rotated-Sorted-Array
    • 34.Find-First-and-Last-Position-of-Element-in-Sorted-Array
    • 35.Search-Insert-Position
    • [50.Pow(x,-n)](Binary-Search/50.Pow(x,-n).md)
    • [69.Sqrt(x)](Binary-Search/69.Sqrt(x).md)
    • 704.Binary-Search
    • 74.Search-a-2D-Matrix
    • 785.Is-Graph-Bipartite?
    • 796.Rotate-String
    • 81.Search-in-Rotated-Sorted-Array-II
    • Count Of Smaller Number
    • Median
    • Search In A Big Sorted Array
  • Binary Tree
    • Serialize And Deserialize
      • 297.Serialize-and-Deserialize-Binary-Tree
      • 428.Serialize-and-Deserialize-N-ary-Tree
      • 449.Serialize-and-Deserialize-BST
    • 100.Same-Tree
    • 101.Symmetric-Tree
    • 1038.Binary-Search-Tree-to-Greater-Sum-Tree
    • 105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal
    • 106.Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal
    • 108.Convert-Sorted-Array-to-Binary-Search-Tree
    • 1110.Delete-Nodes-And-Return-Forest
    • 114.Flatten-Binary-Tree-to-Linked-List
    • 1145.Binary-Tree-Coloring-Game
    • 116.Populating-Next-Right-Pointers-in-Each-Node
    • 117.Populating-Next-Right-Pointers-in-Each-Node-II
    • 129.Sum-Root-to-Leaf-Numbers
    • 144.Binary-Tree-Preorder-Traversal
    • 199.Binary-Tree-Right-Side-View
    • 222.Count-Complete-Tree-Nodes
    • 226.Invert-Binary-Tree
    • 230.Kth-Smallest-Element-in-a-BST
    • 257.Binary-Tree-Paths
    • 270.Closest-Binary-Search-Tree-Value
    • 285.Inorder-Successor-in-BST
    • 337.House-Robber-III
    • 426.Convert-Binary-Search-Tree-to-Sorted-Doubly-Linked-List
    • 510.Inorder-Successor-in-BST-II
    • 543.Diameter-of-Binary-Tree
    • 617.Merge-Two-Binary-Trees
    • 652.Find-Duplicate-Subtrees
    • 653.Two-Sum-IV---Input-is-a-BST
    • 662.Maximum-Width-of-Binary-Tree
    • 669.Trim-a-Binary-Search-Tree
    • 889.Construct-Binary-Tree-from-Preorder-and-Postorder-Traversal
    • 938.Range-Sum-of-BST
    • 94.Binary-Tree-Inorder-Traversal
    • 951.Flip-Equivalent-Binary-Trees
    • 958.Check-Completeness-of-a-Binary-Tree
    • 979.Distribute-Coins-in-Binary-Tree
    • 987.Vertical-Order-Traversal-of-a-Binary-Tree
    • Search Range In Binary Search Tree
  • Bit
    • 307.Range-Sum-Query---Mutable
    • 308.Range-Sum-Query-2D---Mutable
    • 315.Count-of-Smaller-Numbers-After-Self
    • 493.Reverse-Pairs
  • Data Structure
    • Basic Calculator
      • 224.Basic-Calculator
      • 227.Basic-Calculator-II
      • 772.Basic-Calculator-III
      • Basic Claculator Iv
    • 1146.Snapshot-Array
    • 1152.Analyze-User-Website-Visit-Pattern
    • 1167.Minimum-Cost-to-Connect-Sticks
    • 1172.Dinner-Plate-Stacks
    • 1236.Web-Crawler
    • 128.Longest-Consecutive-Sequence
    • 146.LRU-Cache
    • 155.Min-Stack
    • 158.Read-N-Characters-Given-Read4-II---Call-multiple-times
    • 225.Implement-Stack-using-Queues
    • 232.Implement-Queue-using-Stacks
    • 253.Meeting-Rooms-II
    • 263.Ugly-Number
    • 271.Encode-and-Decode-Strings
    • [28.Implement-strStr()](Data-Structure/28.Implement-strStr().md)
    • 281.Zigzag-Iterator
    • 284.Peeking-Iterator
    • 295.Find-Median-from-Data-Stream
    • 314.Binary-Tree-Vertical-Order-Traversal
    • 332.Reconstruct-Itinerary
    • 341.Flatten-Nested-List-Iterator
    • 346.Moving-Average-from-Data-Stream
    • 348.Design-Tic-Tac-Toe
    • 353.Design-Snake-Game
    • 359.Logger-Rate-Limiter
    • 362.Design-Hit-Counter
    • [380.Insert-Delete-GetRandom-O(1)](Data-Structure/380.Insert-Delete-GetRandom-O(1).md)
    • [381.Insert-Delete-GetRandom-O(1)---Duplicates-allowed](Data-Structure/381.Insert-Delete-GetRandom-O
    • 384.Shuffle-an-Array
    • 41.First-Missing-Positive
    • 460.LFU-Cache
    • [470.Implement-Rand10()-Using-Rand7()](Data-Structure/470.Implement-Rand10()-Using-Rand7().md)
    • 49.Group-Anagrams
    • 523.Continuous-Subarray-Sum
    • 528.Random-Pick-with-Weight
    • 535.Encode-and-Decode-TinyURL
    • 545.Boundary-of-Binary-Tree
    • 572.Subtree-of-Another-Tree
    • 588.Design-In-Memory-File-System
    • 622.Design-Circular-Queue
    • 642.Design-Search-Autocomplete-System
    • 692.Top-K-Frequent-Words
    • 706.Design-HashMap
    • 707.Design-Linked-List
    • 729.My-Calendar-I
    • 731.My-Calendar-II
    • 759.Employee-Free-Time
    • 794.Valid-Tic-Tac-Toe-State
    • 84.Largest-Rectangle-in-Histogram
    • 843.Guess-the-Word
    • 900.RLE-Iterator
    • 937.Reorder-Data-in-Log-Files
    • 981.Time-Based-Key-Value-Store
    • 99.Recover-Binary-Search-Tree
    • Add And Search Word Data Structure Design
    • Heapify
    • Max Tree
    • Rehashing
    • Subarray Sum Zero
  • Divide Conquer
    • 102.Binary-Tree-Level-Order-Traversal
    • 103.Binary-Tree-Zigzag-Level-Order-Traversal
    • 104.Maximum-Depth-of-Binary-Tree
    • 107.Binary-Tree-Level-Order-Traversal-II
    • 110.Balanced-Binary-Tree
    • 124.Binary-Tree-Maximum-Path-Sum
    • 173.Binary-Search-Tree-Iterator
    • 218.The-Skyline-Problem
    • 236.Lowest-Common-Ancestor-of-a-Binary-Tree
    • 450.Delete-Node-in-a-BST
    • 973.K-Closest-Points-to-Origin
    • 98.Validate-Binary-Search-Tree
    • Inorder
    • Insert Node In A Binary Search Tree
    • Postorder
    • Preorder
  • Dynamic Programming
    • 1.position
      • 1048.Longest-String-Chain
      • 198.House-Robber
      • 256.Paint-House
      • 265.Paint-House-II
      • 32.Longest-Valid-Parentheses
      • 338.Counting-Bits
      • 361.Bomb-Enemy
      • 403.Frog-Jump
      • 45.Jump-Game-II
      • 518.Coin-Change-2
      • 55.Jump-Game
      • 62.Unique-Paths
      • 63.Unique-Paths-II
      • 64.Minimum-Path-Sum
      • 70.Climbing-Stairs
      • 72.Edit-Distance
      • 85.Maximal-Rectangle
      • 871.Minimum-Number-of-Refueling-Stops
      • 91.Decode-Ways
      • 97.Interleaving-String
      • 980.Unique-Paths-III
    • 2.sequence
      • Sell Stock
        • 188.Best-Time-to-Buy-and-Sell-Stock-IV
        • 309.Best-Time-to-Buy-and-Sell-Stock-with-Cooldown
      • 115.Distinct-Subsequences
      • 132.Palindrome-Partitioning-II
      • 300.Longest-Increasing-Subsequence
      • 472.Concatenated-Words
      • 516.Longest-Palindromic-Subsequence
      • 727.Minimum-Window-Subsequence
      • 801.Minimum-Swaps-To-Make-Sequences-Increasing
      • K Sum
      • Long Common Sequence
      • Maximum Subarray Iii
      • Minimum Adjustment Cost
    • Backpack Problem
      • 1155.Number-of-Dice-Rolls-With-Target-Sum
      • 322.Coin-Change
      • 416.Partition-Equal-Subset-Sum
      • Backpack Ii
      • Backpack Iii
      • Backpack
    • 区间型
      • 1000.Minimum-Cost-to-Merge-Stones
      • 1335.Minimum-Difficulty-of-a-Job-Schedule
      • 375.Guess-Number-Higher-or-Lower-II
      • 87.Scramble-String
      • Coins In A Line Iii
    • 矩阵坐标
      • 1277.Count-Square-Submatrices-with-All-Ones
      • 221.Maximal-Square
      • 741.Cherry-Pickup
    • 1049.Last-Stone-Weight-II
    • 1140.Stone-Game-II
    • 1235.Maximum-Profit-in-Job-Scheduling
    • 1320.Minimum-Distance-to-Type-a-Word-Using-Two-Fingers
    • 1406.Stone-Game-III
    • 774.Minimize-Max-Distance-to-Gas-Station
    • Longest Arithmetic Sequence
  • Graph Search
    • Word Ladder
      • 126.Word-Ladder-II
      • 127.Word-Ladder
    • 10.Regular-Expression-Matching
    • 1041.Robot-Bounded-In-Circle
    • 1066.Campus-Bikes-II
    • 1087.Brace-Expansion
    • 1102.Path-With-Maximum-Minimum-Value
    • 113.Path-Sum-II
    • 1192.Critical-Connections-in-a-Network
    • 1197.Minimum-Knight-Moves
    • 1219.Path-with-Maximum-Gold
    • 1239.Maximum-Length-of-a-Concatenated-String-with-Unique-Characters
    • 1284.Minimum-Number-of-Flips-to-Convert-Binary-Matrix-to-Zero-Matrix
    • 1293.Shortest-Path-in-a-Grid-with-Obstacles-Elimination
    • 131.Palindrome-Partitioning
    • 133.Clone-Graph
    • 1345.Jump-Game-IV
    • 1376.Time-Needed-to-Inform-All-Employees
    • 139.Word-Break
    • 140.Word-Break-II
    • 1416.Restore-The-Array
    • 17.Letter-Combinations-of-a-Phone-Number
    • 179.Largest-Number
    • 200.Number-of-Islands
    • 212.Word-Search-II
    • 22.Generate-Parentheses
    • 248.Strobogrammatic-Number-III
    • 286.Walls-and-Gates
    • 289.Game-of-Life
    • 298.Binary-Tree-Longest-Consecutive-Sequence
    • 301.Remove-Invalid-Parentheses
    • 312.Burst-Balloons
    • 317.Shortest-Distance-from-All-Buildings
    • 320.Generalized-Abbreviation
    • 323.Number-of-Connected-Components-in-an-Undirected-Graph
    • 329.Longest-Increasing-Path-in-a-Matrix
    • 364.Nested-List-Weight-Sum-II
    • 386.Lexicographical-Numbers
    • 39.Combination-Sum
    • 399.Evaluate-Division
    • 40.Combination-Sum-II
    • 417.Pacific-Atlantic-Water-Flow
    • 430.Flatten-a-Multilevel-Doubly-Linked-List
    • 437.Path-Sum-III
    • 44.Wildcard-Matching
    • 463.Island-Perimeter
    • 465.Optimal-Account-Balancing
    • 489.Robot-Room-Cleaner
    • 490.The-Maze
    • 494.Target-Sum
    • 51.N-Queens
    • 515.Find-Largest-Value-in-Each-Tree-Row
    • 524.Longest-Word-in-Dictionary-through-Deleting
    • 529.Minesweeper
    • 547.Number-of-Provinces
    • 568.Maximum-Vacation-Days
    • 675.Cut-Off-Trees-for-Golf-Event
    • 679.24-Game
    • 695.Max-Area-of-Island
    • 698.Partition-to-K-Equal-Sum-Subsets
    • 721.Accounts-Merge
    • 733.Flood-Fill
    • 737.Sentence-Similarity-II
    • 743.Network-Delay-Time
    • 752.Open-the-Lock
    • 753.Cracking-the-Safe
    • 773.Sliding-Puzzle
    • 79.Word-Search
    • 802.Find-Eventual-Safe-States
    • 815.Bus-Routes
    • 818.Race-Car
    • 854.K-Similar-Strings
    • 863.All-Nodes-Distance-K-in-Binary-Tree
    • 864.Shortest-Path-to-Get-All-Keys
    • 909.Snakes-and-Ladders
    • 93.Restore-IP-Addresses
    • 95.Unique-Binary-Search-Trees-II
    • 96.Unique-Binary-Search-Trees
    • 994.Rotting-Oranges
  • Linked List
    • Add Two Numbers
      • 2.Add-Two-Numbers
      • 445.Add-Two-Numbers-II
    • 109.Convert-Sorted-List-to-Binary-Search-Tree
    • 138.Copy-List-with-Random-Pointer
    • 141.Linked-List-Cycle
    • 142.Linked-List-Cycle-II
    • 143.Reorder-List
    • 148.Sort-List
    • 160.Intersection-of-Two-Linked-Lists
    • 19.Remove-Nth-Node-From-End-of-List
    • 206.Reverse-Linked-List
    • 21.Merge-Two-Sorted-Lists
    • 23.Merge-k-Sorted-Lists
    • 234.Palindrome-Linked-List
    • 237.Delete-Node-in-a-Linked-List
    • 24.Swap-Nodes-in-Pairs
    • 25.Reverse-Nodes-in-k-Group
    • 328.Odd-Even-Linked-List
    • 369.Plus-One-Linked-List
    • 61.Rotate-List
    • 82.Remove-Duplicates-from-Sorted-List-II
    • 83.Remove-Duplicates-from-Sorted-List
    • 86.Partition-List
    • 876.Middle-of-the-Linked-List
    • 92.Reverse-Linked-List-II
    • Remove Duplicates From Unsorted List Geeksforgeeks
  • Matrix
    • Spiral Matrix
      • 54.Spiral-Matrix
      • 59.Spiral-Matrix-II
    • 1074.Number-of-Submatrices-That-Sum-to-Target
    • 1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold
    • 240.Search-a-2D-Matrix-II
    • 296.Best-Meeting-Point
    • 304.Range-Sum-Query-2D---Immutable
    • 311.Sparse-Matrix-Multiplication
    • 36.Valid-Sudoku
    • 363.Max-Sum-of-Rectangle-No-Larger-Than-K
    • 37.Sudoku-Solver
    • 48.Rotate-Image
    • 498.Diagonal-Traverse
    • 562.Longest-Line-of-Consecutive-One-in-Matrix
    • 723.Candy-Crush
    • 73.Set-Matrix-Zeroes
    • 835.Image-Overlap
    • 939.Minimum-Area-Rectangle
    • 963.Minimum-Area-Rectangle-II
    • 986.Interval-List-Intersections
    • Friend Circles
  • Mergesort
    • Algorithm Swap
  • Numbers
    • 1088.Confusing-Number-II
    • 13.Roman-to-Integer
    • 166.Fraction-to-Recurring-Decimal
    • 202.Happy-Number
    • 65.Valid-Number
    • 681.Next-Closest-Time
    • 780.Reaching-Points
    • 829.Consecutive-Numbers-Sum
    • 914.X-of-a-Kind-in-a-Deck-of-Cards
    • 991.Broken-Calculator
  • Other
    • 1185.Day-of-the-Week
    • 149.Max-Points-on-a-Line
    • 176.Second-Highest-Salary
    • 20.Valid-Parentheses
    • 277.Find-the-Celebrity
    • 612.Shortest-Distance-in-a-Plane
    • [8.String-to-Integer-(atoi)](Other/8.String-to-Integer-(atoi).md)
  • Permutation And Combination
    • 46.Permutations
    • 47.Permutations-II
    • 60.Permutation-Sequence
    • 77.Combinations
    • 78.Subsets
    • 90.Subsets-II
  • Queue
    • 480.Sliding-Window-Median
    • 853.Car-Fleet
    • 862.Shortest-Subarray-with-Sum-at-Least-K
    • 950.Reveal-Cards-In-Increasing-Order
  • Sort Algorithm
    • 1057.Campus-Bikes
    • 969.Pancake-Sorting
    • Bubble Sort
    • Merge Sort
    • Quick Sort
  • Stack
    • 1130.Minimum-Cost-Tree-From-Leaf-Values
    • 1249.Minimum-Remove-to-Make-Valid-Parentheses
    • 379.Design-Phone-Directory
    • 394.Decode-String
    • 402.Remove-K-Digits
    • 456.132-Pattern
    • 496.Next-Greater-Element-I
    • 503.Next-Greater-Element-II
    • 636.Exclusive-Time-of-Functions
    • 71.Simplify-Path
    • 739.Daily-Temperatures
    • 844.Backspace-String-Compare
    • 917.Reverse-Only-Letters
    • 946.Validate-Stack-Sequences
  • String
    • 1055.Shortest-Way-to-Form-String
    • 1096.Brace-Expansion-II
    • 1100.Find-K-Length-Substrings-With-No-Repeated-Characters
    • 1153.String-Transforms-Into-Another-String
    • 12.Integer-to-Roman
    • 125.Valid-Palindrome
    • 151.Reverse-Words-in-a-String
    • 161.One-Edit-Distance
    • 165.Compare-Version-Numbers
    • 168.Excel-Sheet-Column-Title
    • 171.Excel-Sheet-Column-Number
    • 205.Isomorphic-Strings
    • 214.Shortest-Palindrome
    • 242.Valid-Anagram
    • 3.Longest-Substring-Without-Repeating-Characters
    • 344.Reverse-String
    • 415.Add-Strings
    • 43.Multiply-Strings
    • 443.String-Compression
    • 459.Repeated-Substring-Pattern
    • 482.License-Key-Formatting
    • 5.Longest-Palindromic-Substring
    • 556.Next-Greater-Element-III
    • 557.Reverse-Words-in-a-String-III
    • 567.Permutation-in-String
    • 640.Solve-the-Equation
    • 68.Text-Justification
    • 726.Number-of-Atoms
    • 736.Parse-Lisp-Expression
    • 767.Reorganize-String
    • 784.Letter-Case-Permutation
    • 792.Number-of-Matching-Subsequences
    • 809.Expressive-Words
    • 819.Most-Common-Word
    • 833.Find-And-Replace-in-String
  • Toposort
    • 1136.Parallel-Courses
    • 207.Course-Schedule
    • 210.Course-Schedule-II
    • 269.Alien-Dictionary
    • 444.Sequence-Reconstruction
    • 468.Validate-IP-Address
    • Topological Sorting
  • Trie Tree
    • 1032.Stream-of-Characters
    • 1268.Search-Suggestions-System
    • [208.Implement-Trie-(Prefix-Tree)](Trie-Tree/208.Implement-Trie-(Prefix-Tree).md)
    • 336.Palindrome-Pairs
  • Two Pointers
    • 1004.Max-Consecutive-Ones-III
    • 1099.Two-Sum-Less-Than-K
    • 159.Longest-Substring-with-At-Most-Two-Distinct-Characters
    • 167.Two-Sum-II---Input-array-is-sorted
    • 26.Remove-Duplicates-from-Sorted-Array
    • 27.Remove-Element
    • 340.Longest-Substring-with-At-Most-K-Distinct-Characters
    • 42.Trapping-Rain-Water
    • 647.Palindromic-Substrings
    • 680.Valid-Palindrome-II
    • 75.Sort-Colors
    • 76.Minimum-Window-Substring
    • 88.Merge-Sorted-Array
    • Sort Colors Ii
  • Union Find
    • 1168.Optimize-Water-Distribution-in-a-Village
    • 803.Bricks-Falling-When-Hit
    • 924.Minimize-Malware-Spread
    • 947.Most-Stones-Removed-with-Same-Row-or-Column
Powered by GitBook
On this page
  • 218. The Skyline Problem
  • 题目地址
  • 题目描述
  • 代码
  • Approach 1: Divide and Conquer
  • Approach #2 Sweep line

Was this helpful?

  1. Divide Conquer

218.The-Skyline-Problem

Previous173.Binary-Search-Tree-IteratorNext236.Lowest-Common-Ancestor-of-a-Binary-Tree

Last updated 4 years ago

Was this helpful?

218. The Skyline Problem

题目地址

题目描述

A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B).

Buildings Skyline Contour
The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi], where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX, 0 < Hi ≤ INT_MAX, and Ri - Li > 0. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.

For instance, the dimensions of all buildings in Figure A are recorded as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] .

The output is a list of "key points" (red dots in Figure B) in the format of [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely defines a skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should be considered part of the skyline contour.

For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].

Notes:
The number of buildings in any input list is guaranteed to be in the range [0, 10000].
The input list is already sorted in ascending order by the left x position Li.
The output list must be sorted by the x position.
There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...[2 3], [4 5], [7 5], [11 5], [12 7]...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...[2 3], [4 5], [12 7], ...]

代码

Approach 1: Divide and Conquer

class Solution {
  public List<List<Integer>> getSkyline(int[][] buildings) {
        int n = buildings.length;
    List<List<Integer>> output = new ArrayList<List<Integer>>();

    if (n == 0)    return output;
    if (n == 1)    {
      int xStart = buildings[0][0];
      int xEnd = buildings[0][1];
      int y = buildings[0][2];

      output.add(new ArrayList<Integer>() {{ add(xStart); add(y); }});
      output.add(new ArrayList<Integer>() {{ add(xEnd); add(0); }});

      return output;
    }

    List<List<Integer>> lfetSkyline, rightSkyline;
    leftSkyline = getSkyline(Arrays.copyOfRange(buildings, 0, n / 2));
    rightSkyline = getSkyline(Arrays.copyOfRange(buildings, n / 2, n));

    return mergeSkylines(leftSkyline, rightSkyline);
  }

  public List<List<Integer>> mergeSkylines(List<List<Integer>> left, List<List<Integer>> right) {
    int nL = left.size(), nR = right.size();
    List<List<Integer>> output = new ArrayList<List<Integer>>();

    int x, maxY;
    int pL = 0, pR = 0;
    int currY = 0, leftY = 0, rightY = 0;
    while ((pL < nL) && (pR < nR)) {
      List<Integer> pointL = left.get(pL);
      List<Integer> pointR = right.get(pR);
      // pick up the smallest x
      if (pointL.get(0) < pointR.get(0)) {
        x = pointL.get(0);
        leftY = pointL.get(1);
        pL++;
      } else {
        x = pointR.get(0);
        righY = pointR.get(1);
        pR++;
      }
      maxY = Math.max(leftY, rightY);
      // update output if there is a skyline change
      if (currY != maxY) {
        updateOutput(output, x, maxY);
        currY = maxY;
      }
    }

    appendSkyline(output, left, pL, nL, currY);
    appendSkyline(output, right, pR, nR, currY);

    return output;
  }

  public void updateOutput(List<List<Integer>> output, int x, int y) {
     // if skyline change is not vertical - add the new point
    if (output.isEmpty() || output.get(output.size() - 1).get(0) != x) {
      output.add(new ArrayList<Integer>() {{ add(x); add(y); }}); 
    } else {
    // if skyline change is vertical - update the last point
      output.get(output.size() - 1).set(1, y);
    }
  }

/**
 *  Append the rest of the skyline elements with indice (p, n)
 *  to the final output.
 */
  public void appendSkyline(List<List<Integer>> output, List<List<Integer>> skyline, int p, int n, int currY) {
    while (p < n) {
      List<Integer> point = skyline.get(p);
      int x = point.get(0);
      int y = point.get(1);
      p++;
      // update output if there is a skyline change
      if (currY != y) {
        updateOutput(output, x, y);
        currY = y;
      }
    }
  }

}

Approach #2 Sweep line

本题是经典的sweep line问题。

对于sweep line问题我们需要考虑的只有两点:

1. 延水平方向 / 时间方向 :时间队列 event queue,一般来说是一个优先队列;

2. 延垂直方向 :sweep line status,即当前的扫描线的状态,一般会将交点按照顺序排序;

对于本题来说,sweep line status可以使用一个multi set来进行维护,当然由于在Java中没有multi set,因此需要使用TreeMap来模拟。

event queue的当然是使用优先队列,问题是如何进行排序,这个才是本题的核心难点。

这里给出结论:

大方向是按照x轴排序,如果x轴相等那么按照height排序;

如果x轴相等,优先判断是否是左端点,如果是左端点,那么优先入队;

如果同时是右端点,那么需要反序入队,就是height小的反而需要排在前面。

public List<List<Integer>> getSkyline(int[][] buildings) {
    List<List<Integer>> res = new ArrayList<>();
    // 对于同x轴,优先将左端点入队列
    // 如果同是右端点,则要反序,y小的先入队列
    // 其余按照正常的height顺序排列即可
    PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>(){
        public int compare(int[] o1, int[] o2) {
            if (o1[0] == o2[0] && o1[2] != o2[2]) return o1[2] - o2[2];
            if (o1[0] == o2[0] && o1[2] == 1 && o2[2] == 1) return o1[1] - o2[1];
            return o1[0] == o2[0] ? o2[1] - o1[1] : o1[0] - o2[0];
        }
    });
    TreeMap<Integer, Integer> map = new TreeMap<>();
    for (int[] b : buildings) {
        int s = b[0];
        int e = b[1];
        int h = b[2];
        pq.add(new int[]{s, h, 0});
        pq.add(new int[]{e, h, 1});
    }
    while (!pq.isEmpty()) {
        int[] event = pq.poll();
        int x = event[0];
        int h = event[1];
        int status = event[2];        
        int curr_max = map.size() == 0 ? 0 : map.lastKey();
        if (status == 0) {
            if (h > curr_max) res.add(Arrays.asList(x, h));
            map.put(h, map.getOrDefault(h, 0) + 1);
        } 
        else {
            map.put(h, map.get(h) - 1);
            if (map.get(h) == 0) map.remove(h);
            curr_max = map.size() == 0 ? 0 : map.lastKey();
            if (h > curr_max) res.add(Arrays.asList(x, curr_max));
        }

    }
    return res;
}
https://leetcode.com/problems/the-skyline-problem/