📖
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
  • 一、 运算符
  • 一些小技巧
  • 二、 应用场景
  • 三、 例题
  • 190 颠倒的二进制位
  • 位1的个数
  • 思路一:位运算
  • 思路二:n与n-1做位运算
  • 231 2的幂
  • 两整数之和
  • 405 数字转化为十六进制

Was this helpful?

  1. Basic Knowledge

Bit Operation

PreviousBinary TreeNextHeapify

Last updated 5 years ago

Was this helpful?

一、 运算符

  • & 与运算: 两个位都是 1 时,结果才为 1,否则为 0

  • | 或运算: 两个位都是 0 时,结果才为 0,否则为 1

  • ^ 异或运算: 两个位相同则为 0,不同则为 1

  • ~ 取反运算:0 则变为 1,1 则变为 0

  • << 左移运算:向左进行移位操作,高位丢弃,低位补 0 (每左移一位相当于乘一次2)

  • >> 右移运算:向右进行移位操作,正数右移,高位用 0 补,负数右移,高位用 1 补(每右移一位相当于除一次2)

    • 无符号右移 >>>当负数使用无符号右移时,用 0 进行补位

乘以或除以2的幂数

可以用左移<<和右移>>位运算来代替

i << 2, i >> 2

判断一个数的奇偶性

可以用判断二进制最右的一位来代替,最右位是1则是偶数,是0则是奇数。

i & 1

判断一个数是否是2的幂数

x & (x – 1)

将一个数对应的二进制位的最右边的1置为0

x & (x – 1)

将一个数对应的二进制位的最右边的0置为1

x | (x + 1)

将一个数对应的二进制位的最右边的0置为1,其余位全置为0

¬x & (x + 1)

将一个数对应的二进制位的最右边的1置为0,其余位全置为1

¬x | (x – 1)

将一个数对应的二进制位的右尾端连续的1都置为0

x & (x + 1)

将一个数对应的二进制位的右尾端连续的1都置为0,其余位全置为1

¬x | (x + 1)

将一个数对应的二进制位的右尾端连续的0都置为1

x | (x– 1)

将一个数对应的二进制位的右尾端连续的0都置为1,其余位全置为0

¬ x & (x - 1)

将一个数对应的二进制位仅保留最右边的1,其余为全置为0

x & (−(x-1))

一些小技巧

  • 将数字 A 的第 k 位设置为1:A = A | (1 << (k - 1))

  • 将数字 A 的第 k 位设置为0:A = A & ~(1 << (k - 1))

  • 检测数字 A 的第 k 位:A & (1 << (k - 1)) != 0

  • Extract the lowest set bit 获取数字 A 的最低位:

    A & -A

    或者

    A & ~(A - 1)
    • 例如数字 6(110)的最低位对应 2(10)

  • 得到 111111..111: ~0

二、 应用场景

^ 异或运算性质:

(1)交换律

(2)结合律(即(a^b)^c == a^(b^c))

(3)对于任何数x,都有x^x=0,x^0=x

(4)自反性 A ^ B ^ B = A ^ 0 = A

常见应用:

  • 与运算的应用:(1)清零。如果想将一个单元清零,即使其全部二进制位为0,只要与一个各位都为零的数值相与,结果为零。 (2)取一个数中指定位

  • 或运算的应用: 对一个数的某几位补1

  • 异或运算的应用: 消去一对重复的数(利用上面), 交换变量等等。

  • 取模: 位运算比加减乘除更加高效。 所以在一些底层的组件例如jdk, redis 中经常用位运算,比如用<< ,>>代替乘除, 用& 代替取模操作。

  • 状态压缩和位图: 位运算可以用压缩存储和表示信息。 每个二进制位有0|1 两种状态, 那一个int32 可以表示出 32种状态。 比如linux中的文件状态中的read ,write, 和执行权限就可以用三个二进制位表示, 7(111)表示有Read的权限,有Write的权限和执行的权限。

String intToString(int x) {
        char[] bytes = new char[4];
        for(int i = 3; i > -1; --i) {
            bytes[3 - i] = (char) (x >> (i * 8) & 0xff);
        }
        return new String(bytes);
    }
  // Decodes bytes string to integer
int stringToInt(String bytesStr) {
    int result = 0;
    for(char b : bytesStr.toCharArray()) {
      result = (result << 8) + (int)b;
    }
    return result;
  }

三、 例题

1、 不使用中间变量交换两数

// 思路: 利用上面提到的异或的结合率 和自反率
// a = (a ^ b) ^ b , b = a ^ b ^ a
void swap(int &a, int &b) {
  a ^= b;
  b ^= a;
  a ^= b;
}

2、 数组中,只有一个数出现一次,剩下都出现两次,找出出现一次的数 (leetcode - 136)

    public int singleNumber(int[] nums) {
        int res = 0;
        for(int i = 0; i < nums.length; i++) {
            res = res ^ nums[i];
        }
        return res;
    }

3、 用 O(1) 时间检测整数 n 是否是 2 的幂次 (LintCode - 142)

/** 思路: 常用技巧:n&(n-1)消去n 的二进制最后一位的1
* 比如3&(3-1) = (11)&(10) = (10) , 
* 如果是2的幂次, 那二进制形式下只有一位是1, 消去后为0
*/    
    public boolean checkPowerOf2(int n) {
        if(n <= 0) return false;
        return (n & (n - 1)) == 0;
    }

4、子集列举 (leetcode - 78 medium)

描述:

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

思路:(这道题递归做感觉也很容易理解)

注意数组中数字唯一,可以把这道题理解成高中数学中的排列组合问题。每个数字有取或不取两种可能性, n个数有2的n次方个子集。 可以用一个正整数二进制表示的第i位是1还是0,代表集合的第i个数取或者不取。类似下图:

0 000 {}
1 001 {1}
2 010 {2}
3 011 {1,2}
4 100 {3}
5 101 {1,3}
6 110 {2,3}
7 111 {1,2,3}

A:

    vector<vector<int>> subsets(vector<int>& nums) {
        int n = nums.size()
        int p = 1 << n;
        vector<vector<int>> subs(p);
        for (int i = 0; i < p; i++) {
            for (int j = 0; j < n; j++) {
                // 用 i>>j & 1的方式遍历每一位
                if ((i >> j) & 1) {
                    subs[i].push_back(nums[j]);
                }
            }
        }
        return subs;
    }

5、 位图

描述:有一千万个整数,整数范围在1到1亿之间, 如何快速查找某个整数是否在这1千万个整数中。

思路: 用一个bit 数组来存储这1-1亿之间的数。如果数字存在, 在对应的下标上标1, 1亿个数只需要1亿个bit位。

public class BitMap { // Java 中 char 类型占 16bit,也即是 2 个字节
  private char[] bytes;
  private int nbits;

  public BitMap(int nbits) {
    this.nbits = nbits;
    this.bytes = new char[nbits/16+1];
  }

  public void set(int k) {
    if (k > nbits) return;
    int byteIndex = k / 16;
    int bitIndex = k % 16;
    bytes[byteIndex] |= (1 << bitIndex);
  }

  public boolean get(int k) {
    if (k > nbits) return false;
    int byteIndex = k / 16;
    int bitIndex = k % 16;
    return (bytes[byteIndex] & (1 << bitIndex)) != 0;
  }
}

190 颠倒的二进制位

颠倒给定的 32 位无符号整数的二进制位。

示例1:

输入: 00000010100101000001111010011100
输出: 00111001011110000010100101000000
解释: 输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596,
因此返回 964176192,其二进制表示形式为 00111001011110000010100101000000。
public int reverseBits(int n) {
        int t = 0;
        for(int i = 0;i<32;i++) 
            t+= (1&(n>>i))<<(31-i);
        return t;
    }

位1的个数

编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数。
示例1:
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。

思路一:位运算

利用循环右移操作,每次移动1位,并且取出末尾与1做&操作,若不为1,说明末尾是0。

public int hammingWeight(int n) {
         int cnt = 0;
        for(int i=0;i<32;i++)
        {
            cnt += n&1;
            n >>=1;
        }
        return cnt;
    }

思路二:n与n-1做位运算

当n&(n-1)运算,会把最后一个1的位变成0。

public int hammingWeight(int n) {
        int cnt = 0;
        while (n != 0) {
           ++cnt;
           n = n & (n - 1);
        }
        return cnt;
    }

231 2的幂

给定一个整数,编写一个函数来判断它是否是 2 的幂次方。
示例1:

输入: 1
输出: true
解释: 2^0 = 1

二分查找采用打表和二分查找的方法,将int范围内的所有2^n全部存入一个整数表中,然后对整数表进行二分查找。

public boolean isPowerOfTwo(int n) {
    if (n <= 0) return false;
    return (n & (n - 1)) == 0? true : false;
}

两整数之和

不使用运算符 + 和 - ,计算两整数a、b之和。
示例1:

输入: a = 1, b = 2
输出: 3
不用运算符,考虑位运算。a^b 得到不考虑进位的a+b结果;a&b<<1得到a+b的进位。
public int getSum(int a, int b) {
        while(b!=0) {
            int carry = (a&b)<<1;
            a = a^b;
            b = carry;
        }
        return a;
    }

405 数字转化为十六进制

给定一个整数,编写一个算法将这个数转换为十六进制数。对于负整数,我们通常使用补码运算。

**示例1**:

> 输入:
>  26

输出:
 "1a"

**示例2**:

> 输入:
>  -1

输出:
 "ffffffff"

**注意**:

> 十六进制中所有字母(a-f)都必须是小写。
>  十六进制字符串中不能包含多余的前导零。如果要转化的数为0,那么以单个字符'0'来表示;对于其他情况,十六进制字符串中的第一个字符将不会是0字符。
>  给定的数确保在32位有符号整数范围内。
>  不能使用任何由库提供的将数字直接转换或格式化为十六进制的方法。

**示例1**:

> 输入:
>  26

输出:
 "1a"

**示例2**:

> 输入:
>  -1

输出:
 "ffffffff"

位运算

public String toHex(int num) {
        if(num==0) return "0";
        char[] dict = {'0','1','2','3','4','5','6','7','8','9',
            'a','b','c','d','e','f'};
        StringBuffer sb = new StringBuffer();
        while(num!=0) {
            sb.append(dict[num&0xf]);
            num = num >>> 4;
        }
        return sb.reverse().toString();
    }
https://www.jianshu.com/p/b93ba9e24f97