Leetcode datastructures
- Python
(1) Dict:
a={}
a['x'] = 123
a.pop('x')
a.get('x',0)
del a['x']
a.items()
(2) set
a=set()
a=set([1,2,3])
a.add('x')
a.remove('x')
(3) collections.defaultdict
import collections.defaultdict as defaultdict
a=defaultdict(list)
a['x'].append(1)
(4)collections.deque:
a=deque()
a.append(1)
a.pop()
a.appendleft(1)
a.popleft()
(5) heapq
q=heapq.heapify(list)
heapq.heappush(q,1)
heapq.heappop(q)
q[0] # smallest, min-heap by default
heapq.nlargest(k,q) # q doesn't need to be heap
heapq.nsmallest(k,q) # q doesn't need to heap
(6) collections.Counter
a=Counter([1,1,2,2,2,3])
a[1]
a[1]+=1
a.update([1,1,2])
del a[1]
(7) list
a=[1,2,3]
a.append()
a.pop()
a.copy()
(8) @lru_cache(None)
(9) sorted(iterable, key, reverse=False) # ascending
- C++
https://leetcode.com/discuss/study-guide/1154632/c-stl-powerful-guide-compiled-list-of-popular-stl-operations
(1) vector
vector<int> a;
a.begin() //iterator
a.end()
a.size()
a.empty()
a[0]
a.at(0)
a.front()
a.back()
a.push_back(1)
a.pop_back()
a.erase(index)
a.clear()
for (auto it = vec.begin(); it != vec.end(); ++it) // loop
(2) deque
deque<int> a;
a.begin() //iterator
a.end()
a[0]
a.at(0)
a.front()
a.back()
a.push_front(1)
a.push_back(1)
a.pop_fron()
a.pop_back()
(3) dict
unordered_map is hash table, but map is a balanced search tree which is sorted and search is O(log(N))
//unordered_map
unordered_map<pair<int,int>, int> a;
a[(1,1)] = 1
a.erase((1,1))
a.erase(a.begin())
a.empty() // whether it's empty
a.clear()
if(a.find((1,1)) != a.end()) // search
for (auto& x: a) // x will be a pair of (key, value)
(4) set
unordered_set is hash table, but set is a balanced search tree which is sorted and search is O(log(N))
//unordered_set
unordered_set<int> a;
a.insert(1)
a.erase(1)
a.erase(a.begin())
a.empty() // whether it's empty
a.clear()
if(a.find(1) != a.end()) // search
for (auto& x: a) // loop
(5) string
std::string a = "Hello, World!";
a.clear()
a.size() and a.length() //both can give the number of chars
a += 'hihi'
if(a.find('hi') != string::npos) // search
for (char x: a) // loop
std::string b = 'hihi';
swap(a,b) //exchange their values