力扣 第178场双周赛(A~C)

A:3866. 找到第一个唯一偶数
题意见题目即可,cnt数一下,然后判数目就行。

 1 class Solution {
 2 public:
 3     int firstUniqueEven(vector<int>& nums) {
 4         int n=nums.size();
 5         map<int,int> cnt;
 6         for(int i=0;i<n;i++)
 7             if(nums[i]%2==0)
 8                 cnt[nums[i]]++;
 9 
10         for(int i=0;i<n;i++)
11             if(cnt[nums[i]]==1)
12                 return nums[i];
13         
14         return -1;
15     }
16 };

B:3867. 数对的最大公约数之和
因为gcd函数的复杂度为log级别,所以我们直接按照题意线性模拟就可以。

 1 typedef long long LL;
 2 class Solution {
 3 public:
 4     LL gcd(LL a,LL b){
 5         return b==0?a:gcd(b,a%b);
 6     }
 7     long long gcdSum(vector<int>& nums) {
 8         LL n=nums.size();
 9         vector<LL> pregcd(n,0);
10         LL mx=-1;
11         for(LL i=0;i<n;i++){
12             mx=max(mx,1ll*nums[i]);
13             pregcd[i]=gcd(nums[i],mx);
14         }
15         sort(pregcd.begin(),pregcd.end());
16         LL i=0,j=n-1;
17         LL ans=0;
18         while(i<j){
19             ans+=gcd(pregcd[i],pregcd[j]);
20             i++,j--;
21         }
22         return ans;
23     }
24 };

C:3868. 通过交换使数组相等的最小花费

给定两个数组,交换某个数据内的元素花费为0,交换两数组同一位置的元素花费1。

问最小花费使得两数组相同。

每个元素的cnt必须为偶数,才能保证两数组可能相同,反过来也成立,所以先判一下是否能够相同。

然后,a数组cnt1,总的cnt,如果cnt<cnt1,表示a数组这个元素多了,那么我们需要把这个元素换到b数组,如果cnt>cnt1,表示a数组这个元素少了,需要把这个元素从b数组换到a来,我们只需要考虑第一种情况,因为∑(cnt-cnt1)==0,所以大于零的情况之和 与 小于零的情况之和是抵消的,一次交换,就能把正的情况-1,同时把负的情况+1.

 1 class Solution {
 2 public:
 3     int minCost(vector<int>& nums1, vector<int>& nums2) {
 4         map<int,int> cnt;
 5         for(int x:nums1)
 6             cnt[x]++;
 7         for(int x:nums2)
 8             cnt[x]++;
 9         for(auto [k,v]:cnt){
10             if(v%2==1)
11                 return -1;
12         }
13         map<int,int> cnt1;
14         map<int,int> cnt2;
15         for(int x:nums1)
16             cnt1[x]++;
17         for(int x:nums2)
18             cnt2[x]++;
19         int ans=0;
20         for(auto [k,v]:cnt){
21             int target=v/2;
22             int d=cnt1[k]-target;
23             if(d>0)
24                 ans+=d;
25         }
26         return ans;
27     }
28 };

D:3869. 统计区间内奇妙数的数目

数位dp,后面再来补题。

posted on 2026-03-16 17:10  greenofyu  阅读(2)  评论(0)    收藏  举报