CodeBook
  • Introduction
  • Array
    • Maximum Product of Three Numbers
    • Set Mismatch
    • Find the Duplicate Number
    • Find All Duplicates in an Array
    • Find All Numbers Disappeared in an Array
    • Missing Number
    • Single Number
    • Find Difference
    • Find the Celebrity
    • Word Distance
    • Product of Array Except Self
  • Binary Search
    • First Bad Version
    • Search in a Big Sorted Array
    • Search Range
    • Find the Peak
    • Maximum Number in Mountain Sequence
    • Search in Rotated Sorted Array
    • Find Minimum in Rotated Sorted Array
    • Search a 2D Matrix
    • Search a 2D Matrix II
    • Smallest Rectangle Enclosing Black Pixels
    • [Binary Search] Merge Two Sorted Array
    • Single Element in a Sorted Array
  • Two Pointers
    • 1 Forward
      • Moving Zeros
      • Remove Elements
      • Remove Duplicated
      • Longest Continuous Increasing Subsequence
      • Replace all Occurrences of String AB with C
    • 2 Oppsite
      • Rotate Array
      • Container With Most Water
      • Trapping Rain Water
      • Triangle Count
    • 3 Sliding Windows
      • Permutation in String
      • Find All Anagrams in a String
      • Longest Substring with At Most K Distinct Characters
      • Max Consecutive Ones II
      • Minimum Size Subarray Sum
      • Longest Substring Without Repeating Characters
      • Minimum Window Substring
      • Subarrays with K Different Integers
    • 4 Partition
      • Color Sort
      • Color Sort II
      • Partition Array
    • # Sum
      • Two Sum
      • Two Sum - Unique Pairs
      • Two Sum - Less Or Equal
      • Two Sum - Greater Than Target
      • Two Sum - Closest
      • Two Sum - Difference
      • Two Sum - Data Structure Design
      • Three Sum
      • Three Sum With Multiplicity
      • Three Sum Smaller
      • Three Sum - Triangle Count
      • Four Sum
  • BFS
    • 1 Traverse
      • Number of Islands
      • Clone Gragh
      • Number of Distinct Islands
      • Pacific Atlantic Water Flow
      • Surrounded Regions
      • Walls and Gates
      • Max Area of Island
    • 2 Shortest
      • 01 Matrix
      • Knight Shortest Path
      • Shortest Distance from All Buildings
      • Best Meet Point
      • Shortest Bridge
      • Snakes and Ladders
      • Bus Route
  • DFS
    • 0 Basic
      • Subsets
      • Subsets II
      • Permutations
      • Permutations II
      • Prev/Next Permutation
      • Kth Permutation
      • Permutation Index
      • Combination Sum
      • Combination Sum II
      • Combination Sum III
      • Combination
      • Path Sum
    • 1 Enumeration
      • Cartesian Product
      • Letter Combinations of a Phone Number
      • Split String
      • Palindrome Partitioning
      • Expression Add Operators
      • Target Sum
      • Restore IP Addresses
      • Generate Parentheses
      • Generalized Abbreviation
      • Remove Invalid Parentheses
      • Letter Case Permutation
      • Factor Combinations
      • Find the Missing Number II
    • 2 Search
      • N-Queens
      • Sudoku
      • Employee Importance
      • Increasing Subsequences
      • Nested List Weight Sum
    • 3 Flood Fill
      • Flood Fill
      • Number of Enclaves
    • 4 Path
      • Longest Increasing Path in a Matrix
      • Unique Paths III
    • 5 Memo
      • Knight Dialer
      • Regular Expression Matching
      • Wildcard Matching
    • # Word Big Four
      • Word Break
      • Word Break II
      • Word Pattern
      • Word Pattern II
      • Word Search
      • Word Search II
      • Word Ladder
      • Word Ladder II
  • Tree
    • 0 Binary Search Tree
      • Validate Binary Search Tree
      • Recover Binary Search Tree
      • Minimum Absolute Difference in BST
      • Find Mode in Binary Search Tree
      • Verify Preorder Sequence in Binary Search Tree
      • Unique Binary Search Trees
      • Count of Smaller Numbers After Self
      • Trim a Binary Search Tree
      • Closest Binary Search Tree Value
      • Closest Binary Search Tree Value II
    • 1 Traversal
      • Binary Tree Inorder Traversal
      • Binary Tree Preorder Traversal
      • Binary Tree Postorder Traversal
      • Binary Tree Level Order Traversal
    • 2 Divide and Conquer
      • Balanced Binary Tree
      • Max/Min Depth of Binary Tree
      • Diameter of Tree
      • DiffSum
      • Find Leaves of Binary Tree
    • 3 SubTree
      • Same/Symmetric Tree
      • TreeIsomorphism
      • Subtree of Another Tree
      • Find Duplicate Subtrees
      • Most Frequent Subtree Sum
      • Minimum Subtree
      • Subtree with Maximum Average
      • Equal Tree Partition
      • Flip Binary Tree To Match Preorder Traversal
    • 4 Path
      • Path Sum
      • Path Sum II
      • Path Sum III
      • Path Sum IV
      • Path Sum with Digits Representation
      • Binary Tree Paths
      • Binary Tree Longest Consecutive Sequence
      • Binary Tree Longest Consecutive Sequence II
      • Binary Tree Maximum Path Sum
      • Sum Root to Leaf Numbers
      • Boundary of Binary Tree
      • Smallest String Starting From Leaf
    • 5 Level Order
      • Level Order Traversal
      • Maximum Width of Binary Tree
      • Binary Tree Right Side View
      • Binary Tree Vertical Order Traversal
    • 6 LCA
      • LCA
      • LCA II
      • LCA III
      • LCA IV
      • Smallest Deepest Subtree
      • LCA of a BST
      • Cousins in Binary Tree
    • 7 Build Tree
      • Build Maximum Binary Tree
      • Convert Sorted List to Binary Search Tree
      • Serialize Deserialize
      • Verify Preorder Serialization of a Binary Tree
      • Construct Binary Tree from Traversals
    • 8 Distance
      • Closest Leaf in a Binary Tree
      • All Nodes Distance K in Binary Tree
    • 9 Structure
      • Flatten Binary Tree to Linked List
      • Binary Tree Upside Down
      • BST to Doubly LinkedList
      • Populating Next Right Pointers in Each Node
      • Populating Next Right Pointers in Each Node II
      • Invert Binary Tree
    • # N-ary Tree
  • String
    • 1 Pattern
      • Is Subsequence
      • One Edit Distance
      • Backspace String Compare
    • 2 Implementation
      • Reverse
      • Find the Closest Palindrome
      • Reverse Words in a String
      • Text Justification
    • 3 Substring
      • Implement Str
      • Longest Substring with At Least K Repeating Characters
      • Longest Common Prefix
    • 4 Number
      • Maximum Swap
      • Add Strings
      • Nth Digit
      • Compare Version Numbers
      • String to Integer (atoi)
      • Integer to English Words
      • Integer to Roman
      • Roman to Integer
      • Multiply Strings
      • Reverse Integer
    • 5 Decode
      • Decode String
      • Encode and Decode Strings
    • 6 Palindrome
      • Valid Palindrome
      • Valid Palindrome II
      • Palindrome Number
      • Palindrome Linked List
      • Palindromic Substrings
      • Palindrome Permutation
      • Palindrome Partitioning
      • Find Longest Palindromic Substring
      • Longest Palindromic Subsequence
      • Longest Palindromic Substrings
    • 7 Evaluation
      • Solve the Equation
      • Simplify Path
      • Valid Number
    • 8 Binary String
      • Count Binary Substrings
    • 9 Parenthesis
      • Valid Parenthesis String
      • Valid Parentheses
  • Data Structures
    • 0 Design
      • LRU
      • LFU
    • 1 LinkedList
      • Merge Sort
      • Find Cycle
      • Palindrome Linked List
      • Remove Duplicates
      • Flatten a Multilevel Doubly Linked List
      • Copy List with Random Pointer
    • 2 Stack
      • Min Stack
      • Max Stack
      • Implement Queue by Stacks
      • Implement Stack by Queues
    • 3 Queue/Deque
      • Moving Average
      • Design Circular Queue
      • Design Circular Deque
    • 4 Heap
      • Median for Data Stram
      • Kth Largest Data Stream
      • Top K Words
      • Top K Elements
      • Kth Smallest Number in Sorted Matrix
    • 5 Interval
      • Merge Intervals
      • Insert Interval
      • Non-overlapping Intervals
      • Maximum Length of Pair Chain
      • Meeting Room
      • Merge Two Sorted Interval List
      • Merge K Sorted Interval List
      • Intersection of Two Sorted Intervals
      • Meeting Room II
    • 6 Matrix
      • Multiply Sparse Matrix
      • Matrix Diagonal Traverse
      • Valid Sudoku
      • Spiral Matrix
    • 7 Iterator
      • Flatten 2D Vector
      • Pair Iterator
      • Peeking Iterator
      • Zigzag Iterator
    • 8 Hash
      • Design HashSet
      • Design HashMap
      • Hash Function
      • ReHash
      • Consistent Hash
      • Bloom Filter
      • Robin-Karp Algorithm
  • Advanced Data Structures
    • 1 Trie
      • Implement Trie
      • Stream of Characters
    • 2 Union Find
      • Number of Islands II
      • [Union Find]Graph Connect Tree
      • Minimum Spanning Tree
      • Bricks Falling When Hit
      • Most Stones Removed with Same Row or Column
      • Satisfiability of Equality Equations
    • 3 Monotonous Stack
      • Increasing Triplet Subsequence
      • Largest Rectangle in Histogram
      • Maximal Rectangle
      • Remove K Digits
      • Remove Duplicate Letters
      • Next Greater Element I
      • Next Greater Element II
    • 4 TreeSet/TreeMap
      • My Calendar I
      • My Calendar II
    • 5 Random
      • Shuffle an Array
      • Random Pick with Weight
      • Random Pick Index
    • 6 Binary Index Tree
    • 7 Segment Tree
      • Range Sum Query - Mutable
  • Graph
    • 1 General
      • Graph Deep Copy
    • 2 Topological Sorting
      • Course Schedule
      • Sequence Reconstruction
      • Alien Dictionary
    • 3 Bipartition
      • Is Graph Bipartition
      • Possible Bipartition
    • Detect Cycle in an Undirected Graph
    • Shortest Path in Undirected Graph
    • All Paths From Source to Target
    • Graph Valid Tree
    • Number of Connected Components in an Undirected Graph
    • Minimum Height Trees
  • Dynamic Programming
    • 0 Basic DP
      • Triangle
      • House Robber
      • House Robber II
      • Paint Fence
      • Paint House
    • 1 Sequence DP
      • Decode Ways
    • 2 Match Sequence DP
      • Edit Distance
      • K Edit Distance
      • Longest Common Subsequence
      • Minimum Swaps To Make Sequences Increasing
      • Scramble String
    • 3 Interval DP
      • Burst Ballons
      • Stone Game
    • 4 Matrix DP
      • Number Of Corner Rectangles
      • Max Square
      • Longest Increasing Path in a Matrix
    • 5 Backpack
      • K-Sum
      • Backpack1-01
      • Backpack2-01
      • Backpack4-Complete
      • Backpack3-Complete
      • Backpack7-Multiply
    • 6 Game DP
      • Predict the Winner
      • Can I Win
      • Coins In Line I
      • Coins In Line II
      • Coins In Line III
  • Common Methods
    • 1 Presum
      • Subarray Sum Equals K
      • Continuous Subarray Sum
      • Path Sum II
      • Min/Max Subarry
      • Contiguous 01-Array
      • Flip 01String to Monotone Increasing
      • Maximum Sum of Two Non-Overlapping Subarrays
    • 2 Bucket
      • Maximum Gap
    • 3 Simulation
      • Pour Water
    • 4 Buffer
      • Read N Characters Given Read4 II - Call multiple times
      • Read N Characters Given Read4
      • Third Maximum Number
    • 5 Merge/Union
      • Merge k Sorted Lists
      • Merge k Sorted Arrays
      • Merge k Sorted Intervals
      • Intersection of Three Sorted Array
      • Intersection of Two Arrays
      • Intersection of Two Arrays II
    • 6 Geometry
      • Max Points on a Line
    • 7 Math
      • GCD
      • Matrix Coordinate
      • Sqrt(x)
      • Divide Two Integers
      • pow(x, n)
    • 8 Sorting
      • Merge Sort
      • Quick Sort
      • Quick Select
  • Design/OOD
    • Design Rate Limiter
    • Design Hit Counter
    • Design Twitter
    • Design MapWithExpiration
    • Design Tiny URL
  • Appendix
    • Java Built-in
      • Comparator
      • Stream
      • String Pool
    • Multithreading
      • Synchronized
      • Producer-Consumer
      • CountDownLatch
      • Semaphore
      • Thread Pool
      • DeadLock
      • Inter-thread Communication
Powered by GitBook
On this page
  • 对比 HashSet / HashMap
  • 对比 PriorityQueue(Heap)
  • 常见用法
  • Doc Intro
  • Methods
  1. Advanced Data Structures

4 TreeSet/TreeMap

PreviousNext Greater Element IINextMy Calendar I

Last updated 6 years ago

TreeSet / TreeMap 是底层运用了的数据结构

对比 HashSet / HashMap

  • HashSet / HashMap 存取的时间复杂度为O(1),而 TreeSet / TreeMap 存取的时间复杂度为O(logn)所以在存取上并不占优。

  • HashSet / HashMap 内元素是无序的,而TreeSet / TreeMap 内部是有序的(可以是按自然顺序排列也可以自定义排序)。

  • TreeSet / TreeMap 还提供了类似和这两个其他数据结构没有的方法

    • 对于 TreeSet, 实现上述两个方法的方法为:

      • lowerBound

        • public E lower(E e) --> 返回set中严格小于给出元素的最大元素,如果没有满足条件的元素则返回null。

        • public E floor(E e) --> 返回set中不大于给出元素的最大元素,如果没有满足条件的元素则返回null。

      • upperBound

        • public E higher(E e) --> 返回set中严格大于给出元素的最小元素,如果没有满足条件的元素则返回null。

        • public E ceiling(E e) --> 返回set中不小于给出元素的最小元素,如果没有满足条件的元素则返回null。

    • 对于 TreeMap, 实现上述两个方法的方法为:

      • lowerBound

        • public Map.Entry<K,V> lowerEntry(K key) --> 返回map中严格小于给出的key值的最大key对应的key-value对,如果没有满足条件的key则返回null。

        • public K lowerKey(K key) --> 返回map中严格小于给出的key值的最大key,如果没有满足条件的key则返回null。

        • public Map.Entry<K,V> floorEntry(K key) --> 返回map中不大于给出的key值的最大key对应的key-value对,如果没有满足条件的key则返回null。

        • public K floorKey(K key) --> 返回map中不大于给出的key值的最大key,如果没有满足条件的key则返回null。

      • upperBound

        • public Map.Entry<K,V> higherEntry(K key) --> 返回map中严格大于给出的key值的最小key对应的key-value对,如果没有满足条件的key则返回null。

        • public K higherKey(K key) --> 返回map中严格大于给出的key值的最小key,如果没有满足条件的key则返回null。

        • public Map.Entry<K,V> ceilingEntry(K key)--> 返回map中不小于给出的key值的最小key对应的key-value对,如果没有满足条件的key则返回null。

        • public K ceilingKey(K key) --> 返回map中不小于给出的key值的最小key,如果没有满足条件的key则返回null。

    • lowerBound 与 upperBound 均为二分查找(因此要求有序),时间复杂度为O(logn).

对比 PriorityQueue(Heap)

PriorityQueue是基于Heap实现的,它可以保证队头元素是优先级最高的元素,但其余元素是不保证有序的。

  • 方法时间复杂度对比:

    • 添加元素 add() / offer()

      • TreeSet: O(logn)

      • PriorityQueue: O(logn)

    • 删除元素 poll() / remove()

      • TreeSet: O(logn)

      • PriorityQueue: O(n)

    • 查找 contains()

      • TreeSet: O(logn)

      • PriorityQueue: O(n)

    • 取最小值 first() / peek()

      • TreeSet: O(logn)

      • PriorityQueue: O(1)

常见用法

比如滑动窗口需要保证有序,那么这时可以用到TreeSet,因为TreeSet是有序的,并且不需要每次移动窗口都重新排序,只需要插入和删除(O(logn))就可以了

Doc Intro

This implementation provides guaranteed log(n) time cost for the containsKey,get,putandremoveoperations.

Note that this implementation is not synchronized

public class TreeMap<K,V>   Set<Map.Entry<K,V>>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, Serializable

Methods

  • ceilingKey/floorKey -> include equal

  • lower/highrt -> strictly

Modifier and Type

Method and Description

void

boolean

boolean

void

void

boolean

void

int

A Red-Black tree basedimplementation. The map is sorted according to the of its keys, or by a provided at map creation time, depending on which constructor is used.

<,>

(key)Returns a key-value mapping associated with the least key greater than or equal to the given key, ornullif there is no such key.

(key)Returns the least key greater than or equal to the given key, ornullif there is no such key.

()Removes all of the mappings from this map.

()Returns a shallow copy of thisTreeMapinstance.

<? super>

()Returns the comparator used to order the keys in this map, ornullif this map uses theof its keys.

(key)Returnstrueif this map contains a mapping for the specified key.

(value)Returnstrueif this map maps one or more keys to the specified value.

<>

()Returns a reverse orderview of the keys contained in this map.

<,>

()Returns a reverse order view of the mappings contained in this map.

<<,>>

()Returns aview of the mappings contained in this map.

<,>

()Returns a key-value mapping associated with the least key in this map, ornullif the map is empty.

()Returns the first (lowest) key currently in this map.

<,>

(key)Returns a key-value mapping associated with the greatest key less than or equal to the given key, ornullif there is no such key.

(key)Returns the greatest key less than or equal to the given key, ornullif there is no such key.

(<? super,? super> action)Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.

(key)Returns the value to which the specified key is mapped, ornullif this map contains no mapping for the key.

<,>

(toKey)Returns a view of the portion of this map whose keys are strictly less thantoKey.

<,>

(toKey, boolean inclusive)Returns a view of the portion of this map whose keys are less than (or equal to, ifinclusiveis true)toKey.

<,>

(key)Returns a key-value mapping associated with the least key strictly greater than the given key, ornullif there is no such key.

(key)Returns the least key strictly greater than the given key, ornullif there is no such key.

<>

()Returns aview of the keys contained in this map.

<,>

()Returns a key-value mapping associated with the greatest key in this map, ornullif the map is empty.

()Returns the last (highest) key currently in this map.

<,>

(key)Returns a key-value mapping associated with the greatest key strictly less than the given key, ornullif there is no such key.

(key)Returns the greatest key strictly less than the given key, ornullif there is no such key.

<>

()Returns aview of the keys contained in this map.

<,>

()Removes and returns a key-value mapping associated with the least key in this map, ornullif the map is empty.

<,>

()Removes and returns a key-value mapping associated with the greatest key in this map, ornullif the map is empty.

(key,value)Associates the specified value with the specified key in this map.

(<? extends,? extends> map)Copies all of the mappings from the specified map to this map.

(key)Removes the mapping for this key from this TreeMap if present.

(key,value)Replaces the entry for the specified key only if it is currently mapped to some value.

(key,oldValue,newValue)Replaces the entry for the specified key only if currently mapped to the specified value.

(<? super,? super,? extends> function)Replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.

()Returns the number of key-value mappings in this map.

<,>

(fromKey, boolean fromInclusive,toKey, boolean toInclusive)Returns a view of the portion of this map whose keys range fromfromKeytotoKey.

<,>

(fromKey,toKey)Returns a view of the portion of this map whose keys range fromfromKey, inclusive, totoKey, exclusive.

<,>

(fromKey)Returns a view of the portion of this map whose keys are greater than or equal tofromKey.

<,>

(fromKey, boolean inclusive)Returns a view of the portion of this map whose keys are greater than (or equal to, ifinclusiveis true)fromKey.

<>

()Returns aview of the values contained in this map.

红黑树
lowerBound
upperBound
NavigableMap
natural ordering
Comparator
Map.Entry
K
V
ceilingEntry
K
K
ceilingKey
K
clear
Object
clone
Comparator
K
comparator
natural ordering
containsKey
Object
containsValue
Object
NavigableSet
K
descendingKeySet
NavigableSet
NavigableMap
K
V
descendingMap
Set
Map.Entry
K
V
entrySet
Set
Map.Entry
K
V
firstEntry
K
firstKey
Map.Entry
K
V
floorEntry
K
K
floorKey
K
forEach
BiConsumer
K
V
V
get
Object
SortedMap
K
V
headMap
K
NavigableMap
K
V
headMap
K
Map.Entry
K
V
higherEntry
K
K
higherKey
K
Set
K
keySet
Set
Map.Entry
K
V
lastEntry
K
lastKey
Map.Entry
K
V
lowerEntry
K
K
lowerKey
K
NavigableSet
K
navigableKeySet
NavigableSet
Map.Entry
K
V
pollFirstEntry
Map.Entry
K
V
pollLastEntry
V
put
K
V
putAll
Map
K
V
V
remove
Object
V
replace
K
V
replace
K
V
V
replaceAll
BiFunction
K
V
V
size
NavigableMap
K
V
subMap
K
K
SortedMap
K
V
subMap
K
K
SortedMap
K
V
tailMap
K
NavigableMap
K
V
tailMap
K
Collection
V
values
Collection