1.分割圆的最少切割次数
分割圆的最少切割次数
Solution
class Solution {
public:
int numberOfCuts(int n) {
int tmp = 360 / n;
if(n == 1) return 0;
if(n % 2 == 0) return n / 2;
return n;
}
};
2.行和列中一和零的差值
行和列中一和零的差值
Solution
class Solution {
public:
vector<vector<int>> onesMinusZeros(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
int rcnt[n][2], ccnt[m][2];
memset(rcnt,0,sizeof(rcnt));
memset(ccnt,0,sizeof(ccnt));
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
rcnt[i][grid[i][j]]++;
ccnt[j][grid[i][j]]++;
}
}
vector<vector<int>> ans(n, vector<int>(m));
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
ans[i][j] = rcnt[i][1] + ccnt[j][1] - rcnt[i][0] - ccnt[j][0];
}
}
return ans;
}
};
3.商店的最少代价
商店的最少代价
Solution
class Solution {
public:
int bestClosingTime(string customers) {
int n = customers.size();
vector<int> p1(n+1, 0); // 关门
vector<int> p2(n+1, 0); // 开门
for(int i=n-1;i>=0;i--) {
p1[i] = p1[i+1] + (customers[i] == 'Y');
}
for(int i=0;i<n;i++) {
p2[i+1] = p2[i] + (customers[i] == 'N');
}
int idx, ans = INT_MAX;
for(int i=0;i<=n;i++) { // 第i小时关门,
int cost = p1[i] + p2[i];
if(cost < ans) {
ans = cost;
idx = i;
}
}
return idx;
}
};
4.统计回文子序列数目
统计回文子序列数目
Solution
class Solution {
const long MOD = 1e9 + 7;
public:
int countPalindromes(string s) {
int suf[10]{}, suf2[10][10]{}, pre[10]{}, pre2[10][10]{};
for (int i = s.length() - 1; i >= 0; --i) {
char d = s[i] - '0';
for (int j = 0; j < 10; ++j)
suf2[d][j] += suf[j];
++suf[d];
}
long ans = 0L;
for (char d : s) {
d -= '0';
--suf[d];
for (int j = 0; j < 10; ++j)
suf2[d][j] -= suf[j]; // 撤销
for (int j = 0; j < 10; ++j)
for (int k = 0; k < 10; ++k)
ans += (long) pre2[j][k] * suf2[j][k]; // 枚举所有字符组合
for (int j = 0; j < 10; ++j)
pre2[d][j] += pre[j];
++pre[d];
}
return ans % MOD;
}
};