- 第一题
简单题
class Solution {
public:
bool haveConflict(vector<string>& event1, vector<string>& event2) {
if((event1[0] < event2[0] && event2[0] <= event1[1])||(event2[0] < event1[0] && event1[0] <= event2[1])){
return true;
}
return false;
}
};
- 第二题
求数组的最大公约数,judge函数是重点
class Solution {
public:
bool judge(vector<int>& nums, int b, int e, int k){
int i = b;
int max = gcd(nums[b], nums[e]);
while(i <= e){
max = gcd(max, nums[i]);
if(max < k) return false;
i++;
}
if(max == k) return true;
return false;
}
int subarrayGCD(vector<int>& nums, int k) {
int size = nums.size();
int ans = 0;
for(int i = 0; i < size; i++){
for(int j = i; j >= 0; j--){
if(judge(nums,j,i,k)){
ans++;
}
}
}
return ans;
}
};
- 第三题
数学题,求中位数
class Solution {
public:
long long minCost(vector<int>& nums, vector<int>& cost) {
long long sum = accumulate(cost.begin(), cost.end(), 0LL);
int size = nums.size();
vector<pair<int, int>> vec;
for(int i = 0; i < size; ++i){
vec.push_back({nums[i], cost[i]});
}
sort(vec.begin(), vec.end());
long long now = 0;
int target = vec[0].first;
for(int i = 0; i < size; i++){
now += (long long)(vec[i].second);
if(now > sum / 2){
target = vec[i].first;
break;
}
}
long long ans = 0;
for(int i = 0; i < size; ++i){
ans += abs(target - vec[i].first) *(long long)(vec[i].second);
}
return ans;
}
};
- 第四题
偶数只能变偶数,奇数只能变奇数。
class Solution {
public:
long long makeSimilar(vector<int>& nums, vector<int>& target) {
vector<int> nums1;
vector<int> nums2;
vector<int> target1;
vector<int> target2;
int size = target.size();
for(int i = 0; i < size; i++){
if(nums[i] % 2 == 0){
nums1.push_back(nums[i]);
}else{
nums2.push_back(nums[i]);
}
if(target[i]%2==0){
target1.push_back(target[i]);
}else{
target2.push_back(target[i]);
}
}
sort(nums1.begin(), nums1.end());
sort(target1.begin(), target1.end());
sort(nums2.begin(), nums2.end());
sort(target2.begin(), target2.end());
long long sum = 0;
size = nums1.size();
for(int i = 0; i < size; i++){
if(target1[i] > nums1[i]){
sum += target1[i] - nums1[i];
}
}
size = nums2.size();
for(int i = 0; i < size; i++){
if(target2[i] > nums2[i]){
sum += target2[i] - nums2[i];
}
}
return sum / 2;
}
};