第一题:多个数组求交集
思路:刚开始看到题目确实吓到了,因为很难但是看到数据发现可以直接模拟,用一个长度为1100的数组来存储i在二维数组中出现的次数a[i],如果一个数出现的次数为二维数组的长度,则该数在每个数组中都出现过,因为(二维数组的一行)一个数组中的数都各不相同
代码:
class Solution {
public:
vector<int> intersection(vector<vector<int>>& nums) {
int n = nums.size();
int a[1010];
memset(a, 0, sizeof a);
for(auto i : nums){
for(auto j : i)
a[j] ++;
}
vector<int> ans;
for(int i = 1; i <= 1000; i ++)
if(a[i] == n)
ans.push_back(i);
return ans;
}
};
第二题:统计圆内格点的数目
思路:因为这题的数据的点最大为400*400 (400 = 200 + 200)但是最开始我却算成了200*200 * 200*200 我是傻子,然后想了半天,突然发现我算错了,啊啊啊啊。。。。。因为r<=min(x, y)所以所有圆的全部区域都在第一象限,因为这题的最远的点只是(400, 400),最坏的情况时间复杂度为200*400*400,也就是On(16000000),所有可以直接模拟一个a[400][400]的bool数组,对第一象限的(0, 0)到(400, 400)的正方形区域的所有点进行判断该点是否在圆内
代码:
class Solution {
public:
int distanc(int x1, int y1, int x2, int y2){
return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
}
int countLatticePoints(vector<vector<int>>& circles) {
bool a[410][410];
memset(a, false, sizeof a);
for(auto i : circles){
int x = i[0], y = i[1], c = i[2];
for(int j = x - c; j <= x + c; j ++)
for(int k = y - c; k <= y + c; k ++){
if(distanc(j, k, x, y) <= c * c)
a[j][k] = true;
}
}
int cnt = 0;
for(int i = 0; i < 410; i ++)
for(int j = 0; j < 410; j ++)
if(a[i][j]) cnt ++;
return cnt;
}
};
第三题:统计包含每个点的矩阵数目
思路:因为矩阵的纵坐标和查询点的纵坐标都是小于等于100的,所以可以用纵坐标来模拟,用一个长度为101的数组(数组的每个元素为一个动态数组)来存储矩阵中的点,数组的下标来存储纵坐标,数组元素(一个动态数组)来存储横坐标,排序,对points数组中的纵坐标开始到100找到大于等于该点的横坐标的点的个数(二分查找)。
代码:
class Solution {
public:
vector<int> countRectangles(vector<vector<int>>& rectangles, vector<vector<int>>& points) {
vector<int> ans[101];
for(auto &t : rectangles){
ans[t[1]].push_back(t[0]);
}
for(auto &i : ans)
sort(i.begin(), i.end());
int n = points.size();
vector<int> res(n);
for(int i = 0; i < n; i ++){
for(int j = points[i][1]; j <= 100; j ++){
res[i] += ans[j].end() - lower_bound(ans[j].begin(), ans[j].end(), points[i][0]);
}
}
return res;
}
};
第四题:花旗内花的数目
思路:我看到这题就感觉是离散化+差分,这个y总讲过模板,可是我学艺不精忘记了怎么写的,最后只能放弃,后来我看看了y总写的模板又会了。用一个数组来存储花期的开始和结束还有看花的时间,因为这些点都是离散的,将这些点排序好并从1开始编号放入数组中,差分处理(花期开始时+1,结束后-1),通过前缀和来计算答案。。。额。。我感觉我会是会但是说思路的话可能还是不是很好理解,因为这个离散化确实有点难理解,但是y总讲的确实很好理解(我应该是说不出来)
代码
class Solution {
public:
vector<int> ans;
int a[150010];
int find(int x){
int i = 0, j = ans.size() - 1;
while(i < j){
int mid = (i + j) >> 1;
if(ans[mid] >= x) j = mid;
else i = mid + 1;
}
return i + 1;
}
vector<int> fullBloomFlowers(vector<vector<int>>& flowers, vector<int>& persons) {
for(auto i : flowers){
int x = i[0], y = i[1];
ans.push_back(x);
ans.push_back(y);
}
for(auto i : persons) ans.push_back(i);
sort(ans.begin(), ans.end());
ans.erase(unique(ans.begin(), ans.end()), ans.end());
for(auto i : flowers){
a[find(i[0])] ++;
a[find(i[1]) + 1] --;
}
for(int i = 1; i <= ans.size(); i ++) a[i] += a[i - 1];
for(auto i : flowers){
cout << a[find(i[0])] << " " << a[find(i[1])] << endl;
}
int n = persons.size();
vector<int> res(n, 0);
for(int i = 0; i < n; i ++){
res[i] = a[find(persons[i])];
}
return res;
}
};
总结:感觉我的模拟还是有点差的,还有有些虽然做过但是还是不会,以后要把做过的题完全都弄懂并且多练有些模拟。