演算法筆記-Map
Map
可以儲存 key
以及其對應 value
的容器,內部會按照 key
的值進行排序,有以下幾個常見的操作:
- insert 加入元素
- erase 刪除元素
- count 確認該元素是否存在
- find 回傳元素位置
- empty 確認是否為空
- size 回傳元素個數
- clear 清空所有元素
Unordered Map
可以儲存 key
以及其對應 value
的容器,內部不會進行排序,而是使用雜湊表的方式進行一對一的對應,利於查詢對應元素的關係,可以使用的函數與 map
類似。
比較:
容器 | map | unordered_map |
---|---|---|
結構 | 紅黑樹 | 雜湊表 |
內部資料 | 有序 | 無序 |
查詢速度 | 較低 | 較高 |
通常在不要求內部元素有排序的情況下,會使用查詢效率較高的 unordered_map
。
操作
遍歷
使用指針指向開頭,進行遍歷,使用 first
取 key
、second
取 value
。
1 | for(auto i = m.begin(); i != m.end(); i++){ |
替代
在某些 key
值數量較少的情況下,例如 a ~ z 字母
或是 1 ~ 100 的數字
,可以直接使用 vector
等容器,直接以索引值代表 key
並且儲存對應的 value
。
練習
LeetCode 49. Group Anagrams
Given an array of strings strs
, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = [“eat”,“tea”,“tan”,“ate”,“nat”,“bat”]
Output: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = [“a”]
Output: [[“a”]]
Solution:
1 | class Solution { |
利用同字母異序詞
中字母經過排序之後會變為相同字串的特性,將其作為 key
值就可以將他們分組。
LeetCode 149. Max Points on a Line
Given an array of points
where points[i] = [xi, yi]
represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.
Return the max sliding window.
Example 1:

Input: points = [[1,1],[2,2],[3,3]]
Output: 3
Example 2:

Input: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
Solution:
1 | class Solution { |
使用雙重迴圈遍歷所有點,每次固定一個點,以他與其他點之間連線的斜率作為 key
值,value
儲存連線斜率相同的點數量,在判斷時要注意避免分母為 0 的情況。