T1:按身高排序
给你一个字符串数组 names ,和一个由 互不相同 的正整数组成的数组 heights 。两个数组的长度均为 n 。
对于每个下标 i,names[i] 和 heights[i] 表示第 i 个人的名字和身高。
请按身高 降序 顺序返回对应的名字数组 names 。
这个题的关键就是将names和heights联系起来。有两种思路:一是用pair来存储这两者,还有一种就是用map,键值放身高,values放names。
前几次周赛都有用到哈希表,所以这一次我依然是用哈希表来解决这个题目。
class Solution {
public:
vector<string> sortPeople(vector<string>& names, vector<int>& heights) {
map<int ,int>mp;
for(int i = 0 ; i < heights.size(); i++){
mp[heights[i]] = i ;
}
vector<string> res;
for(auto&[height,count]:mp){
res.push_back(names[count]);
}
reverse(res.begin() , res.end());
return res;
}
};
T2:按位与最大的最长子数组
class Solution {
public:
int longestSubarray(vector<int>& nums) {
int res = 1;
int maxm = 0;
for(auto& x: nums) maxm = max(maxm, x);
int cnt = 0;
for(auto& x: nums) {
if(x == maxm) cnt ++;
else {
res = max(res, cnt);
cnt = 0;
}
}
res = max(res, cnt);
return res;
}
};
acwingT1:两个素数
题目的思路很简单,先找出1-x的所有素数,存储在一个数组中,然后再用双指针做法找到符合条件的a b就好了。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main(){
int x ;
cin >> x;
vector<int>sushu;
int i = 0;
int j = 0;
for (i = 2; i <= x; i++)
{
for (j = 2; j < i; j++)
{
if (i%j == 0)
{
break;
}
}
if (j >= i)
{
sushu.push_back(i);
}
}
int n = sushu.size();
int l = 0 , r = n-1;
while(l <= r){
if( sushu[l] * sushu[r] == x){
cout << sushu[l] <<' '<< sushu[r] << endl;
break;
}
if(sushu[l] * sushu[r] > x){
r--;
}
if(sushu[l] * sushu[r] < x){
l++;
}
}
return 0;
}
T2:减法操作
这个题目首先有一种情况是很好确定不能操作实现目的的:因为每种操作都是是数组少2,所以如果原始数组的元素之和为一个奇数,那么一定不能通过这两种操作达到数组全为0。然后对比两种操作,我们应该将更复杂的操作放在前面,明显减2的操作只要满足数组种全部都是偶数,那么我们一定可以通过减2的操作使数组元素全部变为0。
所以现在的问题就简化成可不可以通过题目中的第二种操作,使每个数组元素都变为0或偶数。
我们可以找到第一次出现奇数的位置,为了使其变为奇数,有两种方案:1)前面相邻元素和本身减1;2)本身和后面相邻元素减1;
第一种方案会牵连到前面的全部偶数,然而对于前面的偶数来说,不管是多少个都不能再通过操作二实现全部变为偶数。故对于一个奇数来说,其操作方案是唯一的,就是向后操作。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 200010;
int a[N];
int n;
bool check(){
for(int i = 0 ; i < n-1 ;i ++){
if(a[i] % 2 != 0 )
a[i] -- , a[i+1]--;
}
for(int i = 0 ; i < n ; i++){
if(a[i] < 0 || a[i] %2 != 0) return false;
}
return true;
}
int main(){
cin >> n;
int sum = 0;
for(int i = 0 ; i < n; i++){
cin >> a[i];
sum += a[i];
}
if(sum % 2 != 0 ){
cout <<"NO"<< endl;
return 0;
}
if(check()) cout << "YES"<< endl;
else cout << "NO"<< endl;
return 0;
}