目录
一 多个数组求交集
1.题目
2.思路
这个直接遍历数组,看每个数出现的次数就好了
3.代码
class Solution {
vector<int> ans;
public:
vector<int> intersection(vector<vector<int>>& nums) {
vector<int> ans;
int n=nums.size();
map<int,int> mp;
for(vector<int> vec:nums){
for(int i=0;i<vec.size();i++){
mp[vec[i]]++;
}
}
for(pair<int,int> it:mp){
if(it.second==n){
ans.push_back(it.first);
}
}
return ans;
}
};
二 统计圆内格点数目
1.题目
2.思路
1.枚举点
2.枚举圆
3.维护差分数组
3.代码
//枚举点
class Solution {
public:
int countLatticePoints(vector<vector<int>>& circles) {
int ans = 0;
for (int i = 0; i <= 200; i ++)
for (int j = 0; j <= 200; j ++) {
bool ok = false;
for (int k = 0; k < circles.size(); k ++) {
int x = circles[k][0], y = circles[k][1], r = circles[k][2];
if ((x - i) * (x - i) + (y - j) * (y - j) <= r * r) {
ok = true;
break;
}
}
ans += ok;
}
return ans;
}
};
//枚举圆
class Solution {
int ans=0;
public:
int grid[450][450]={0};
int countLatticePoints(vector<vector<int>>& circles) {
for(vector<int> vec:circles){
int x=vec[0],y=vec[1],r=vec[2];
int x_MAX=x+r,x_MIN=x-r,y_MAX=y+r,y_MIN=y-r;
for(int i=x_MIN;i<=x_MAX;i++){
for(int j=y_MIN;j<=y_MAX;j++){
if(distance(x,y,i,j,r)){
grid[i][j]=1;
}
}
}
}
for(int i=0;i<450;i++){
for(int j=0;j<450;j++){
ans+=grid[i][j];
}
}
return ans;
}
bool distance(int x,int y,int i,int j,int r){
int dx=abs(x-i);
int dy=abs(y-j);
return dx*dx+dy*dy<=r*r;
}
};
三 统计包含每个点的矩形数目
1.题目
2.思路
因为x的数据范围过大,所以这里能够很自然地想到用y的坐标来计算
具体见代码注释
3.代码
class Solution {
public:
const int maxn = 110;
vector<int> countRectangles(vector<vector<int>>& rectangles, vector<vector<int>>& points) {
// 由于横坐标范围较大,此处采用纵坐标作为下标索引,记录纵坐标对应的横坐标集合
vector<vector<int>> a(maxn);
int n = points.size();
for (const auto& x: rectangles) {
a[x[1]].push_back(x[0]);
}
// 对每个纵坐标下横坐标进行排序,后面二分找位置
for (int i = 1; i <= 100; ++i) {
sort(a[i].begin(), a[i].end());
}
vector<int> ans(n, 0);
for (int i = 0; i < n; ++i) {
int x = points[i][0];
int y = points[i][1];
// y位置后的纵坐标都满足,只需遍历每个纵坐标下有多少坐标满足横坐标大于等于x
for (int j = y; j <= 100; ++j) {
// 横坐标已有序,直接二分定位即可
if (!a[j].empty()) {
// 第一个大于等于x之后的元素都满足
ans[i] += a[j].size() - (lower_bound(a[j].begin(), a[j].end(), x) - a[j].begin());
}
}
}
return ans;
}
};
四 花期内花的数目
1.题目
2.思路
和第三题一样
3.代码
//come fro what-is-me
int op[50004],cl[50004];
class Solution {
public:
vector<int> fullBloomFlowers(vector<vector<int>>& flowers, vector<int>& persons) {
int n=flowers.size();
vector<int> ret(persons);
for(int i=0;i<n;++i)op[i]=flowers[i][0],cl[i]=flowers[i][1];
sort(op,op+n),sort(cl,cl+n);
for(int&t:ret){
int o=upper_bound(op,op+n,t)-op;
int e=upper_bound(cl,cl+n,t-1)-cl;
t=o-e;
}
return ret;
}
};