YuezhenQin / javase

Implement Data Structures and Algorithms (Sorting, Searching, Greedy, DP) from Sketch
2 stars 1 forks source link

Map: HashMap, TreeMap #32

Open YuezhenQin opened 11 months ago

YuezhenQin commented 11 months ago

A Map is an object that maps keys to values, or is a collection of key-value pairs. It models the function abstraction in mathematics.

YuezhenQin commented 9 months ago

Anytime you need to count anything, think about using a hash map to do it.

  1. k distinct chars: Find the length of the longest substring that contains at most k distinct characters.
  2. top k: Find the k most frequent elements.
YuezhenQin commented 9 months ago

How to increment a HashMap value in Java?

map.put(map.getOrDefault(key, 0) + 1)

YuezhenQin commented 8 months ago

TreeMap

YuezhenQin commented 8 months ago

Find the Key associated with max Value in a Java Map

Map.Entry<Integer, Integer> maxEntry = null;

for (Map.Entry<Integer, Integer> entry : map.entrySet())
{
    if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0)
    {
        maxEntry = entry;
    }
}