LintCode & LeetCode
  • Introduction
  • Linked List
    • Sort List
    • Merge Two Sorted Lists
    • Merge k Sorted Lists
    • Linked List Cycle
    • Linked List Cycle II
    • Add Two Numbers II
    • Add Two Numbers
    • Odd Even Linked List
    • Intersection of Two Linked Lists
    • Reverse Linked List
    • Reverse Linked List II
    • Remove Linked List Elements
    • Remove Nth Node From End of List
    • Middle of the Linked List
    • Design Linked List
      • Design Singly Linked List
      • Design Doubly Linked List
    • Palindrome Linked List
    • Remove Duplicates from Sorted List
    • Remove Duplicates from Sorted List II
    • Implement Stack Using Singly Linked List
    • Copy List with Random Pointer
  • Binary Search
    • Search in Rotated Sorted Array
    • Search in Rotated Sorted Array II
    • Search in a Sorted Array of Unknown Size
    • First Bad Version
    • Find Minimum in Rotated Sorted Array
    • Find Minimum in Rotated Sorted Array II
    • Find Peak Element
    • Search for a Range
    • Find K Closest Elements
    • Search Insert Position
    • Peak Index in a Mountain Array
    • Heaters
  • Hash Table
    • Jewels and Stones
    • Single Number
    • Subdomain Visit Count
    • Design HashMap
    • Design HashSet
    • Logger Rate Limiter
    • Isomorphic Strings
    • Minimum Index Sum of Two Lists
    • Contains Duplicate II
    • Contains Duplicate III
    • Longest Consecutive Sequence
    • Valid Sudoku
    • Distribute Candies
    • Shortest Word Distance
    • Shortest Word Distance II
  • String
    • Rotate String
    • Add Binary
    • Implement strStr()
    • Longest Common Prefix
    • Reverse Words in a String
    • Reverse Words in a String II
    • Reverse Words in a String III
    • Valid Word Abbreviation
    • Group Anagrams
    • Unique Email Addresses
    • Next Closest Time
    • License Key Formatting
    • String to Integer - atoi
    • Ransom Note
    • Multiply Strings
    • Text Justification
    • Reorder Log Files
    • Most Common Word
    • Valid Parenthesis String
    • K-Substring with K different characters
    • Find All Anagrams in a String
    • Find the Closest Palindrome
    • Simplify Path
  • Array
    • Partition Array
    • Median of Two Sorted Arrays
    • Intersection of Two Arrays
    • Intersection of Two Arrays II
    • Maximum Subarray Sum
    • Minimum Subarray Sum
    • Maximum Subarray II
    • Maximum Subarray III
    • Subarray Sum Closest
    • Subarray Sum
    • Plus One
    • Maximum Subarray Difference
    • Maximum Subarray IV
    • Subarray Sum Equals K
    • Intersection of Two Arrays
    • Intersection of Two Arrays II
    • Find Pivot Index
    • Rotate Array
    • Get Smallest Nonnegative Integer Not In The Array
    • Maximize Distance to Closest Person
    • Sort Colors
    • Next Permutation
    • Rotate Image
    • Pour Water
    • Prison Cells After N Days
    • Majority Element
    • Can Place Flowers
    • Candy
  • Matrix
    • Spiral Matrix
    • Set Matrix Zeroes
    • Diagonal Traverse
  • Queue
    • Design Circular Queue
    • Implement Queue using Stacks
    • Implement Queue by Two Stacks
    • Implement Stack using Queues
    • Moving Average from Data Stream
    • Walls and Gates
    • Open the Lock
    • Sliding Window Maximum
    • Implement Queue Using Fixed Length Array
    • Animal Shelter
  • Stack
    • Valid Parentheses
    • Longest Valid Parentheses
    • Min Stack
    • Max Stack
    • Daily Temperatures
    • Evaluate Reverse Polish Notation
    • Next Greater Element I
    • Next Greater Element II
    • Next Greater Element III
    • Largest Rectangle in Histogram
    • Maximal Rectangle
    • Car Fleet
  • Heap
    • Trapping Rain Water II
    • The Skyline Problem
    • Top K Frequent Words
    • Top K Frequent Words II
    • Top K Frequent Elements
    • Top k Largest Numbers
    • Top k Largest Numbers II
    • Minimum Cost to Hire K Workers
    • Kth Largest Element in an Array
    • Kth Smallest Number in Sorted Matrix
    • Kth Smallest Sum In Two Sorted Arrays
    • K Closest Points to the Origin
    • Merge K Sorted Lists
    • Merge K Sorted Arrays
    • Top K Frequent Words - Map Reduce
  • Data Structure & Design
    • Hash Function
    • Heapify
    • LRU Cache
    • LFU Cache
    • Rehashing
    • Stack Sorting
    • Animal Shelter
    • Sliding Window Maximum
    • Moving Average from Data Stream
    • Find Median from Data Stream
    • Sliding Window Median
    • Design Hit Counter
    • Read N Characters Given Read4 II - Call multiple times
    • Read N Characters Given Read4
    • Flatten 2D Vector
    • Flatten Nested List Iterator
    • Design Search Autocomplete System
    • Time Based Key-Value Store
    • Design Tic-Tac-Toe
    • Insert Delete GetRandom O(1)
  • Union Find
    • Find the Connected Component in the Undirected Graph
    • Find the Weak Connected Component in the Directed Graph
    • Graph Valid Tree
    • Number of Islands
    • Number of Islands II
    • Surrounded Regions
    • Most Stones Removed with Same Row or Column
    • Redundant Connection
  • Trie
    • Implement Trie
    • Add and Search Word
    • Word Search II
    • Longest Word in Dictionary
    • Palindrome Pairs
    • Trie Serialization
    • Trie Service
    • Design Search Autocomplete System
    • Typeahead
  • Trees
    • Binary Tree Inorder Traversal
    • Binary Tree Postorder Traversal
    • Binary Tree Preorder Traversal
    • Binary Tree Level Order Traversal
    • Binary Tree Zigzag Level Order Traversal
    • Binary Tree Vertical Order Traversal
    • N-ary Tree Level Order Traversal
    • N-ary Tree Preorder Traversal
    • N-ary Tree Postorder Traversal
    • Construct Binary Tree from Preorder and Inorder Traversal
    • Populating Next Right Pointers in Each Node
    • Populating Next Right Pointers in Each Node II
    • Maximum Depth of Binary Tree
    • Symmetric Tree
    • Validate Binary Search Tree
    • Convert Sorted Array to Binary Search Tree
    • Path Sum
    • Path Sum II
    • Path Sum III
    • Binary Tree Maximum Path Sum
    • Kth Smallest Element in a BST
    • Same Tree
    • Lowest Common Ancestor of a Binary Tree
    • Lowest Common Ancestor of a Binary Search Tree
    • Nested List Weight Sum II
    • BST Node Distance
    • Minimum Distance (Difference) Between BST Nodes
    • Closet Common Manager
    • N-ary Tree Postorder Traversal
    • Serialize and Deserialize Binary Tree
    • Serialize and Deserialize N-ary Tree
    • Diameter of a Binary Tree
    • Print Binary Trees
  • Segment Tree
    • Segment Tree Build
    • Range Sum Query - Mutable
  • Binary Indexed Tree
  • Graph & Search
    • Clone Graph
    • N Queens
    • Six Degrees
    • Number of Islands
    • Number of Distinct Islands
    • Word Search
    • Course Schedule
    • Course Schedule II
    • Word Ladder
    • Redundant Connection
    • Redundant Connection II
    • Longest Increasing Path in a Matrix
    • Reconstruct Itinerary
    • The Maze
    • The Maze II
    • The Maze III
    • Topological Sorting
    • Island Perimeter
    • Flood Fill
    • Cheapest Flights Within K Stops
    • Evaluate Division
    • Alien Dictionary
    • Cut Off Trees for Golf Event
    • Jump Game II
    • Most Stones Removed with Same Row or Column
  • Backtracking
    • Subsets
    • Subsets II
    • Letter Combinations of a Phone Number
    • Permutations
    • Permutations II
    • Combinations
    • Combination Sum
    • Combination Sum II
    • Combination Sum III
    • Combination Sum IV
    • N-Queens
    • N-Queens II
    • Generate Parentheses
    • Subsets of Size K
  • Two Pointers
    • Two Sum II
    • Triangle Count
    • Trapping Rain Water
    • Container with Most Water
    • Minimum Size Subarray Sum
    • Minimum Window Substring
    • Longest Substring Without Repeating Characters
    • Longest Substring with At Most K Distinct Characters
    • Longest Substring with At Most Two Distinct Characters
    • Fruit Into Baskets
    • Nuts & Bolts Problem
    • Valid Palindrome
    • The Smallest Difference
    • Reverse String
    • Remove Element
    • Max Consecutive Ones
    • Max Consecutive Ones II
    • Remove Duplicates from Sorted Array
    • Remove Duplicates from Sorted Array II
    • Move Zeroes
    • Longest Repeating Character Replacement
    • 3Sum With Multiplicity
    • Merge Sorted Array
    • 3Sum Smaller
    • Backspace String Compare
  • Mathematics
    • Ugly Number
    • Ugly Number II
    • Super Ugly Number
    • Sqrt(x)
    • Random Number 1 to 7 With Equal Probability
    • Pow(x, n)
    • Narcissistic Number
    • Rectangle Overlap
    • Happy Number
    • Add N Days to Given Date
    • Reverse Integer
    • Greatest Common Divisor or Highest Common Factor
  • Bit Operation
    • IP to CIDR
  • Random
    • Random Pick with Weight
    • Random Pick Index
    • Linked List Random Node
  • Dynamic Programming
    • House Robber
    • House Robber II
    • House Robber III
    • Longest Increasing Continuous Subsequence
    • Longest Increasing Continuous Subsequence II
    • Coins in a Line
    • Coins in a Line II
    • Coins in a Line III
    • Maximum Product Subarray
    • Longest Palindromic Substring
    • Stone Game
    • Burst Balloons
    • Perfect Squares
    • Triangle
    • Pascal's Triangle
    • Pascal's Triangle II
    • Min Cost Climbing Stairs
    • Climbing Stairs
    • Unique Paths
    • Unique Paths II
    • Minimum Path Sum
    • Word Break
    • Word Break II
    • Range Sum Query - Immutable
    • Decode Ways
    • Edit Distance
    • Unique Binary Search Trees
    • Unique Binary Search Trees II
    • Maximal Rectangle
    • Maximal Square
    • Regular Expression Matching
    • Wildcard Matching
    • Flip Game II
    • Longest Increasing Subsequence
    • Target Sum
    • Partition Equal Subset Sum
    • Coin Change
    • Jump Game
    • Can I Win
    • Maximum Sum Rectangle in a 2D Matrix
    • Cherry Pick
  • Knapsack
    • Backpack
    • Backpack II
    • Backpack III
    • Backpack IV
    • Backpack V
    • Backpack VI
    • Backpack VII
    • Coin Change
    • Coin Change II
  • High Frequency
    • 2 Sum Closest
    • 3 Sum
    • 3 Sum Closest
    • Sort Colors II
    • Majority Number
    • Majority Number II
    • Majority Number III
    • Best Time to Buy and Sell Stock
    • Best Time to Buy and Sell Stock II
    • Best Time to Buy and Sell Stock III
    • Best Time to Buy and Sell Stock IV
    • Two Sum
    • Two Sum II - Input array is sorted
    • Two Sum III - Data structure design
    • Two Sum IV - Input is a BST
    • 4 Sum
    • 4 Sum II
  • Sorting
  • Greedy
    • Jump Game II
    • Remove K Digits
  • Minimax
    • Nim Game
    • Can I Win
  • Sweep Line & Interval
    • Meeting Rooms
    • Meeting Rooms II
    • Merge Intervals
    • Insert Interval
    • Number of Airplanes in the Sky
    • Exam Room
    • Employee Free Time
    • Closest Pair of Points
    • My Calendar I
    • My Calendar II
    • My Calendar III
    • Add Bold Tag in String
  • Other Algorithms and Data Structure
    • Huffman Coding
    • Reservoir Sampling
    • Bloom Filter
    • External Sorting
    • Construct Quad Tree
  • Company Tag
    • Google
      • Guess the Word
      • Raindrop on Sidewalk
    • Airbnb
      • Display Pages (Pagination)
    • Amazon
  • Problem Solving Summary
    • String or Array Rotation
    • Tips for Avoiding Bugs
    • Substring or Subarray Search
    • Sliding Window
    • K Sums
    • Combination Sum Series
    • Knapsack Problems
    • Depth-first Search
    • Large Number Operation
    • Implementation - Simulation
    • Monotonic Stack & Queue
    • Top K Problems
    • Java Interview Tips
      • OOP in Java
      • Conversion in Java
      • Data Structures in Java
    • Algorithm Optimization Tips
  • Reference
Powered by GitBook
On this page
  • HashMap
  • Union Find (Disjoint Set)
  • 并查集可以干什么?
  • 并查集的操作
  • 并查集完整模板
  • Trie
  • Linked List vs ArrayList
  • Heap
  • Resources
  • Stack
  • Queue
  • ArrayDeque / Deque
  • Arrays
  • TreeSet / TreeMap
  • TreeMap
  • TreeSet

Was this helpful?

Data Structure & Design

PreviousTop K Frequent Words - Map ReduceNextHash Function

Last updated 5 years ago

Was this helpful?

HashMap

HashMap 的两种遍历方式 第一种

  Map map = new HashMap();
  Iterator iter = map.entrySet().iterator();
  while (iter.hasNext()) {
      Map.Entry entry = (Map.Entry) iter.next();
      Object key = entry.getKey();
      Object val = entry.getValue();
  }

效率高,以后一定要使用此种方式!

第二种

  Map map = new HashMap();
  Iterator iter = map.keySet().iterator();
      while (iter.hasNext()) {
      Object key = iter.next();
      Object val = map.get(key);
  }

效率低,以后尽量少使用!

Map Traverse:

Map<String, Integer> map = new HashMap();
// Keys
for(String str : map.keySet()){
    Integer value = map.get(str);
}

// Map.Entry
for (Map.Entry<K, V> e : map.entrySet())
    System.out.println(e.getKey() + ": " + e.getValue());

The Collection view methods allow a Map to be viewed as a Collection in these three ways:

  • keySet — the Set of keys contained in the Map.

  • values — The Collection of values contained in the Map. This Collection is not a Set, because multiple keys can map to the same value.

  • entrySet — the Set of key-value pairs contained in the Map. The Map interface provides a small nested interface called Map.Entry, the type of the elements in this Set.

Differences Between HashMap Vs HashSet In Java

Union Find (Disjoint Set)

并查集: 一种用来解决集合查询合并的数据结构 支持O(1) find / O(1) union

并查集可以干什么?

  1. 判断在不在同一个集合中。

    • find 操作

  2. 关于集合合并

    • union 操作

并查集的操作

  1. 查询 Find (递归? 非递归?)

模板代码

HashMap<Integer, Integer> father = new HashMap<Integer, Integer>();

int find(int x) {
    int parent = x;
    while (parent ! = father.get(parent)) {
        parent = father.get(parent);
    }
    return parent;
}
  1. 合并 Union

老大哥之间合并 跟小弟没关系

HashMap<Integer, Integer> father = new HashMap<Integer, Integer>();

void union(int x, int y) {
    int fa_x = find(x);
    int fa_y = find(y);
    if (fa_x != fa_y) {
        father.put(fa_x, fa_y);
    }
}

并查集完整模板

class UnionFind {
    UnionFind() {}
    HashMap<Integer, Integer> father = new HashMap<Integer, Integer>();
    int find(int x) {
        int parent = x;
        while (parent ! = father.get(parent)) {
            parent = father.get(parent);
        }
        return parent;
    }
    void union(int x, int y) {
        int fa_x = find(x);
        int fa_y = find(y);
        if (fa_x != fa_y) {
            father.put(fa_x, fa_y);
        }
    }
}

Trie

Linked List vs ArrayList

LinkedList and ArrayList are two different implementations of the List interface. LinkedList implements it with a doubly-linked list. ArrayList implements it with a dynamically re-sizing array.

LinkedList<E> allows for constant-time insertions or removals using iterators, but only sequential access of elements.

ArrayList<E>, on the other hand, allow fast random read access, so you can grab any element in constant time.

ArrayList

LinkedList

1) ArrayList internally uses a dynamic array to store the elements.

LinkedList internally uses a doubly linked list to store the elements.

2) Manipulation with ArrayList is slow because it internally uses an array. If any element is removed from the array, all the bits are shifted in memory.

Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory.

3) An ArrayList class can act as a list only because it implements List only.

LinkedList class can act as a list and queue both because it implements List and Deque interfaces.

4) ArrayList is better for storing and accessing data.

LinkedList is better for manipulating data.

Heap

Heap

A min-heap is a binary tree such that

  • the data contained in each node is less than (or equal to) the data in that node’s children.

  • the binary tree is complete

A max-heap is a binary tree such that

  • the data contained in each node is greater than (or equal to) the data in that node’s children.

  • the binary tree is complete

Sift Up

void siftup(int id) {
    while (parent(id) > -1) {
        int parentId = parent(id);
        if (comparesmall(heap.get(parentId), heap.get(id)) == true) {
            break;
        } else {
            swap(id, parentId);
        }
        id = parentId;
    }
}

Sift Down

void siftdown(int id) {
    while (lson(id) < heap.size()) {
        int leftId = lson(id);
        int rightId = rson(id);
        int son;
        if (rightId >= heap.size() || (comparesmall(heap.get(leftId), heap.get(rightId)) == true)) {
            son = leftId;
        } else {
            son = rightId;
        }

        if (comparesmall(heap.get(id), heap.get(son)) == true) {
            break;
        } else {
            swap(id, son);
        }
        id = son;
    }
}

Resources

Stack

Queue

ArrayDeque / Deque

ArrayDeque

  • It’s not thread-safe

  • Null elements are not accepted

  • Works significantly faster than the synchronized Stack

  • Is a faster queue than LinkedList due to the better locality of reference

  • Most operations have amortized constant time complexity

  • An Iterator returned by an ArrayDeque is fail-fast

  • ArrayDeque automatically doubles the size of an array when head and tail pointer meets each other while adding an element

An ArrayDeque implementation can be used as a Stack (Last-In-First-Out) or a Queue(First-In-First-Out).

In Java Docs for ArrayDeque:

Deque Interface:

Arrays

java.util.Arrays

Methods

1.static List asList(T… a): This method returns a fixed-size list backed by the specified array.

// Java program to demonstrate 
// Array.asList() method 

import java.util.Arrays; 

public class Main { 
    public static void main(String[] args) 
    { 

        // Get the Array 
        int intArr[] = { 10, 20, 15, 22, 35 }; 

        // To convert the elements as List 
        System.out.println("Integer Array as List: "
                        + Arrays.asList(intArr)); 
    } 
}
  1. static int binarySearch(elementToBeSearched): These methods searches for the specified element in the array with the help of Binary Search algorithm.

// Java program to demonstrate 
// Array.binarySearch() method 

import java.util.Arrays; 

public class Main { 
    public static void main(String[] args) 
    { 

        // Get the Array 
        int intArr[] = { 10, 20, 15, 22, 35 }; 

        Arrays.sort(intArr); 

        int intKey = 22; 

        System.out.println(intKey 
                        + " found at index = "
                        + Arrays 
                                .binarySearch(intArr, intKey)); 
    } 
}
  1. copyOf(originalArray, newLength): This method copies the specified array, truncating or padding with the default value (if necessary) so the copy has the specified length.

// Java program to demonstrate 
// Array.copyOf() method 

import java.util.Arrays; 

public class Main { 
    public static void main(String[] args) 
    { 

        // Get the Array 
        int intArr[] = { 10, 20, 15, 22, 35 }; 

        // To print the elements in one line 
        System.out.println("Integer Array: "
                        + Arrays.toString(intArr)); 

        System.out.println("\nNew Arrays by copyOf:\n"); 

        System.out.println("Integer Array: "
                        + Arrays.toString( 
                                Arrays.copyOf(intArr, 10))); 
    } 
}
  1. fill(originalArray, fillValue): This method assigns this fillValue to each index of this array.

// Java program to demonstrate 
// Array.fill() method 

import java.util.Arrays; 

public class Main { 
    public static void main(String[] args) 
    { 

        // Get the Arrays 
        int intArr[] = { 10, 20, 15, 22, 35 }; 

        int intKey = 22; 

        Arrays.fill(intArr, intKey); 

        // To fill the arrays 
        System.out.println("Integer Array on filling: "
                        + Arrays.toString(intArr)); 
    } 
}

TreeSet / TreeMap

TreeMap

Default Sorting in TreeMap

@Test
public void givenTreeMap_whenOrdersEntriesNaturally_thenCorrect() {
    TreeMap<Integer, String> map = new TreeMap<>();
    map.put(3, "val");
    map.put(2, "val");
    map.put(1, "val");
    map.put(5, "val");
    map.put(4, "val");

    assertEquals("[1, 2, 3, 4, 5]", map.keySet().toString());
}

Custom Sorting in TreeMap

public void givenTreeMap_whenOrdersEntriesByComparator_thenCorrect() {
    TreeMap<Integer, String> map = 
      new TreeMap<>(Comparator.reverseOrder());
    map.put(3, "val");
    map.put(2, "val");
    map.put(1, "val");
    map.put(5, "val");
    map.put(4, "val");

    assertEquals("[5, 4, 3, 2, 1]", map.keySet().toString());
}

TreeSet

Operations like add, remove and contains (search) take O(log n) time while operations like printing n elements in sorted order require O(n) time.

Set<String> treeSet = new TreeSet<>();

Comparator

Set<String> treeSet = new TreeSet<>(Comparator.comparing(String::length));

Although TreeSet isn’t thread-safe, it can be synchronized externally using the Collections.synchronizedSet() wrapper:

 Set<String> syncTreeSet = Collections.synchronizedSet(treeSet);

TreeSet add()

TreeSet contains()

TreeSet remove()

TreeSet & TreeMap

The TreeSet internally depends on a backing NavigableMap which gets initialized with an instance of TreeMap when an instance of the TreeSet is created:

public TreeSet() {
    this(new TreeMap<E,Object>());
}

This class is likely to be faster than when used as a stack, and faster than when used as a queue.

In this implementation, objects are sorted and stored in ascending order according to their natural order. The _TreeSet _uses a self-balancing binary search tree, more specifically .

https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html
https://javaconceptoftheday.com/differences-between-hashmap-vs-hashset-in-java/
When to use LinkedList over ArrayList?
ArrayList vs LinkedList in Java
Difference between ArrayList and LinkedList
bubkoo.com 常见排序算法 - 堆排序 (Heap Sort)
Data Structures Heap, Heap Sort & Priority Queue
Priority Queue Implementation
CMU: Trees Heaps & Other Trees
Stack
LinkedList
https://docs.oracle.com/javase/8/docs/api/java/util/Deque.html
https://www.geeksforgeeks.org/array-class-in-java/
https://www.baeldung.com/java-treemap
https://www.baeldung.com/java-tree-set
a _Red-Black _tree