5448.判断路径是否相交
集合查找
class Solution {
public:
bool isPathCrossing(string path) {
set<pair<int,int>> s;
int curx = 0;
int cury = 0;
s.insert(make_pair(curx,cury));
for(int i=0;i<path.length();i++)
{
char op = path[i];
if(op=='N'){
curx++;
}
else if(op=='S'){
curx--;
}
else if(op=='E'){
cury++;
}
else{
cury--;
}
if(s.find(make_pair(curx,cury))!=s.end())
{
return true;
}
//cout<<curx<<" "<<cury<<endl;
s.insert(make_pair(curx,cury));
}
return false;
}
};
5449.检查数组对是否可以被k整除
解题思路
按照余数分类,用哈希表存储余数的个数,然后进行配对。
(x+y) % k = 0
则((x%k+k)%k + (y%k+k)%k)%k = 0
代码
class Solution {
public:
bool canArrange(vector<int>& arr, int k) {
unordered_map<int,int> m;
for(int val:arr)
{
int modules = (val%k+k)%k;
m[modules]++;
}
for(auto it=m.begin();it!=m.end();it++)
{
int modules = it->first;
int cnt1 = it->second;
if(modules==0)
{
if(cnt1%2==1)
return false;
}
else{
int modules2 = (k-modules);
int cnt2 = m[modules2];
if(cnt1!=cnt2)
return false;
}
}
return true;
}
};
5450.满足条件的子序列数目
解题思路
双指针+快幂函
代码
const int MOD = 1e9+7;
int quickpow(int x,int n)
{
if(n==0)
return 1;
if(n&1){
return ((long)x*(long)quickpow(x,n-1))%MOD;
}
else{
int tmp = quickpow(x,n/2)%MOD;
return ((long)tmp*(long)tmp)%MOD;
}
}
class Solution {
public:
int numSubseq(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int le = 0;
int ri = nums.size()-1;
int sum = 0;
while(le<=ri){
if(nums[le]+nums[ri]<=target)
{
sum += quickpow(2,ri-le);
sum %= MOD;
le++;
}
else{
ri--;
}
}
return sum;
}
};
5451.满足不等式的最大值
解题思路
优先队列
代码
class Solution {
public:
//yi+yj+|xi-xj| = xj + yj + yi - xi; (i<j)
//即对于每一个xj+yj找到最大的yi-xi即可
int findMaxValueOfEquation(vector<vector<int>>& points, int k) {
priority_queue<pair<int, int>> que;
int res = INT_MIN, j = 1;
for(int i = 0; i < points.size(); i ++){
while(j < points.size() && points[j][0] - points[i][0] <= k){
//压入{xj+yj, xj}
que.push(make_pair(points[j][0]+points[j][1],points[j][0]));
j ++;
}
while(!que.empty()){
//如果xj<=xi
if(que.top().second <= points[i][0])
que.pop();
else{
//res = max(res, yi-xi+yj+xj)
res = max(res, points[i][1] - points[i][0] + que.top().first);
break;
}
}
}
return res;
}
};