python and c++ data structures and operations

Leetcode datastructures

  1. 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

  1. 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
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值