NO.1
思路:哈希+质数判断。
代码实现:
#include <iostream>
#include<string>
#include<cmath>
using namespace std;
bool isprime(int n)
{
if(n<2) return false;
for(int i=2;i<=sqrt(n);i++)
{
if(n%i==0) return false;
}
return true;
}
string s;
int main() {
cin>>s;
int sum[26]={0};
for(auto ch:s)
{
sum[ch-'a']++;
}
int maxn=0,minn=1000;
for(int i=0;i<26;i++)
{
if(sum[i])
{
maxn=max(sum[i],maxn);
minn=min(sum[i],minn);
}
}
if(isprime(maxn-minn))
{
cout<<"Lucky Word"<<endl;
cout<<maxn-minn<<endl;
}
else {
{
cout<<"No Answer"<<endl;
cout<<0<<endl;
}
}
return 0;
}
NO.2
思路:先给左端点进行排序,如果该区间的左端点小于前一个区间的右端点那么就返回false,反之返回true。
代码实现:
class Solution {
public:
bool hostschedule(vector<vector<int> >& schedule) {
sort(schedule.begin(),schedule.end());
for(int i=1;i<schedule.size();i++)
{
if(schedule[i][0]<schedule[i-1][1]) return false;
}
return true;
}
};
NO.3
思路: 背包问题:原问题转换成,从 n 个数中选,总和恰好为 sum / 2,能否挑选出来。
代码实现:
#include <iostream>
using namespace std;
const int N = 510, M = 510 * 110 / 2;
int n;
int arr[N];
int dp[N][M];
int main()
{
cin >> n;
int sum = 0;
for (int i = 1; i <= n; i++)
{
cin >> arr[i];
sum += arr[i];
}
if (sum % 2 == 1) cout << "false" << endl;
else
{
sum /= 2;
dp[0][0] = true;
for (int i = 1; i <= n; i++)
{
for (int j = 0; j <= sum; j++)
{
dp[i][j] = dp[i - 1][j];
if (j >= arr[i])
{
dp[i][j] = dp[i][j] || dp[i - 1][j - arr[i]];
}
}
}
if (dp[n][sum]) cout << "true" << endl;
else cout << "false" << endl;
}
return 0;
}