tantan的博客

Notes, ideas, and observations

Just Monika!

位运算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
unsigned to_uword(const string &word) {
unsigned res = 0;
for (auto &&c: word) {
res |= 1 << (c - 'a');
}
return res;
}

int maxProduct(vector<string>& words) {
vector<unsigned> uwords;
uwords.reserve(words.size());
for (auto &&w: words) {
uwords.push_back(to_uword(w));
}

int m = 0;
int n = words.size();
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
auto &s1 = uwords[i];
auto &s2 = uwords[j];
if (s1 & s2) continue;
if (int r = words[i].size() * words[j].size(); r > m) m = r;
}
}
return m;
}
};

ARP协议

ARP 协议的全称是 Address Resolution Protocol(地址解析协议),它是一个通过解析网络层地址来找寻数据链路层地址的网络传输协议,它在IPv4中极其重要。是IPv4能够正常工作的基础。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* @param {number[]} nums
* @return {number[]}
*/
var findErrorNums = function(nums) {
let ex = new Array(nums.length);
let dup,lost;
for(num of nums){
if (!ex[num-1]){
ex[num-1]=1;
}else{
dup=num;
}
}
for(let i=0;i<nums.length;i++){
if(!ex[i]){
lost=i+1;
break;
}
}
return [dup, lost]
};

Rabin-Karp 算法

字符串匹配算法之一,利用哈希进行匹配比较,利用滚动哈希优化哈希函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* @param {number[]} rating
* @return {number}
*/
var numTeams = function (rating) {
var count = 0;
for (let i = 1; i < rating.length - 1; i++) {
let ri = rating[i];
let countx1 = 0, countx2 = 0;
let county1 = 0, county2 = 0;
for (let x = 0; x < i; x++) {
if (rating[x] < ri) countx1++;
if (rating[x] > ri) countx2++;
}
for (let x = i + 1; x < rating.length; x++) {
if (rating[x] < ri) county1++;
if (rating[x] > ri) county2++;
}
count += countx1 * county2 + countx2 * county1;
}
return count;
};

排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* @param {number[]} costs
* @param {number} coins
* @return {number}
*/
var maxIceCream = function (costs, coins) {
costs.sort((a, b) => a - b);
let count = 0;
for (var i = 0; i < costs.length; i++) {
if (costs[i] <= coins) {
coins -= costs[i];
count++;
} else {
break;
}
}
return count;
};

python 自定义 JSON Encoder

继承 json.JSONEncoder 类, 重载 default 方法

0%