tantan的博客

Notes, ideas, and observations

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 方法

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
31
32
33
34
35
36
37
class Solution
{
public:
ListNode *reverseKGroup(ListNode *head, int k)
{
ListNode _header(0, head);
ListNode *last = &_header;
head = last;
int count = 0;
while (head) {
head = head->next;
count++;
if (head && count == k) {
count -= k;
ListNode *tmp_last_next = last->next;
reverseK(last, k);
head = last = tmp_last_next;
}
}
return _header.next;
}

void reverseK(ListNode *start, int k)
{
ListNode *cur = start, *next = start->next;
int count = 0;
while (count < k) {
ListNode *tmp = next->next;
next->next = cur;
cur = next;
next = tmp;
count++;
}
start->next->next = next;
start->next = cur;
}
};

What is Japanese

#Japanese Sound System

0%