第75场双周赛

6033. 转换数字的最少位翻转次数 - 力扣(LeetCode) (leetcode-cn.com)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int minBitFlips(int start, int goal) {
int bit = 1;
uint32_t t = start, t1 = goal;
int res = 0, i = 0;
while (start != goal) {
int x = (start >> i) & 1;
int y = (goal >> i) & 1;
if (x != y) {
if (y == 0) {
start &= ~(1 << i);
} else {
start |= (1 << i);
}
res ++;
}
i ++;

}
return res;
}
};

6034. 数组的三角和 - 力扣(LeetCode) (leetcode-cn.com)

模拟队列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int triangularSum(vector<int>& nums) {
queue<int> q;
for (auto num: nums) q.push(num);
int bunner = nums.size() - 1, i = 0;
while (q.size() != 1) {
int a = q.front();
q.pop();
int b = q.front();
int sum = a + b;
q.push(sum % 10);
i ++;
if (i == bunner) {
q.pop();
i = 0;
bunner = q.size() - 1;
}
}
return q.front();
}
};

空间复杂度1做法

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int triangularSum(vector<int>& nums) {
int n = nums.size();
for (int i = n - 1; i > 0; i --)
for (int j = 0; j < i; j ++)
nums[j] = (nums[j] + nums[j + 1]) % 10;
return nums[0];
}
};

6035. 选择建筑的方案数 - 力扣(LeetCode) (leetcode-cn.com)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
long long numberOfWays(string s) {
long long n1 = 0, n01 = 0, n10 = 0, n0 = 0;
long long res = 0;
for (auto &c: s) {
if (c == '1') {
n01 += n0;
n1 ++;
res += n10;
} else {
n10 += n1;
n0 ++;
res += n01;
}
}
return res;
}
};

前缀和

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:
long long numberOfWays(string s) {
int n = s.size();
vector<int> count(n, 0);
int zeroCount = 0, oneCount = 0;
for (int i = n - 1; i >= 0; i --) {
if (s[i] == '0') {
count[i] = oneCount;
} else {
count[i] = zeroCount;
}
zeroCount += s[i] == '0' ? 1 : 0;
oneCount += s[i] == '1' ? 1 : 0;
}
zeroCount = oneCount = 0;
long long res = 0;
for (int i = 0; i < n; i ++) {
if (s[i] == '0') {
count[i] *= oneCount;
} else {
count[i] *= zeroCount;
}
zeroCount += s[i] == '0' ? 1 : 0;
oneCount += s[i] == '1' ? 1 : 0;
res += count[i];
}
return res;
}
};

6036. 构造字符串的总得分和 - 力扣(LeetCode) (leetcode-cn.com)

字符串哈希+二分

扩展kmp


第75场双周赛
https://2w1nd.github.io/2022/04/03/LC周赛/第75场双周赛/
作者
w1nd
发布于
2022年4月3日
许可协议