1.
class Solution {
public List<Integer> intersection(int[][] nums) {
List<Integer> list = new ArrayList<>();
int[] res = new int[1001];
for(int[] num:nums){
for(int i=0;i<num.length;i++){
res[num[i]]++;
}
}
for(int i=0;i<res.length;i++){
if(res[i]==nums.length){
list.add(i);
}
}
return list;
}
}
2.
6042. 统计圆内格点数目
模拟,圆包括的最大范围内
class Solution {
public int countLatticePoints(int[][] circles) {
int maxX = 0, maxY = 0, minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE;
for (int[] c : circles) {
minX = Math.min(minX, c[0] - c[2]);
minY = Math.min(minY, c[1] - c[2]);
maxX = Math.max(maxX, c[0] + c[2]);
maxY = Math.max(maxY, c[1] + c[2]);
}
int res = 0;
for (int i = minX; i <= maxX; i++) {
for (int j = minY; j <= maxY; j++) {
for (int[] c : circles) {
int tmp = (i - c[0]) * (i - c[0]) + (j - c[1]) * (j - c[1]);
if (tmp <= c[2] * c[2]) {
res++;
break;
}
}
}
}
return res;
}
}
3
class Solution {
public int[] countRectangles(int[][] rectangles, int[][] points) {
//哈希表key为高度,List为宽度的集合。
HashMap<Integer, List<Integer>> map = new HashMap<>();
for (int[] rectangle : rectangles) {
int l = rectangle[0];
int h = rectangle[1];
List<Integer> list = map.getOrDefault(h, new ArrayList<>());
list.add(l);
map.put(h, list);
}
//由于需要对宽度的列表使用二分法,所以需要排序。
for (int key : map.keySet()) {
Collections.sort(map.get(key));
}
int[] ans = new int[points.length];
for (int i = 0; i < points.length; i++) {
int[] p = points[i];
int x = p[0];
int y = p[1];
int count = 0;
//本题重点,枚举可能的高度,并找到当前高度下,合法的矩形数量。
for (int h = 100; h >= 1; h--) {
//枚举高度已经比point的高度还小了,不可能再找到合法矩形了。
if (h < y) break;
//不存在以当前h为高度的矩形,跳过。
if (!map.containsKey(h)) continue;
//二分搜索,并累加答案
count += binarySearch(map.get(h), x);
}
ans[i] = count;
}
return ans;
}
public int binarySearch(List<Integer> nums, int k) {
//二分法找nums中有多少元素大于等于k。
int n = nums.size();
int left = 0;
int right = n - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums.get(mid) >= k) {
right = mid;
} else {
left = mid + 1;
}
}
return nums.get(right) >= k ? n - right : 0;
}
}
4
class Solution {
public int[] fullBloomFlowers(int[][] flowers, int[] persons) {
List<Integer> in = new ArrayList<>();
List<Integer> out = new ArrayList<>();
for (int[] f : flowers) {
in.add(f[0]);
out.add(f[1]);
}
in.sort((o1, o2) -> o1 - o2);
out.sort((o1, o2) -> o1 - o2);
int[] res = new int[persons.length];
for (int i = 0; i < persons.length; i++) {
int left = 0,right=in.size()-1;
int cnt = 0;
//计算开花数量
while(left<right){
int mid = left+(right-left+1)/2;
if(in.get(mid)>persons[i]){
right = mid-1;
}else{
left = mid;
}
}
if(in.get(left)<=persons[i]){
cnt+=(left+1);
}
//计算凋谢数量
left = 0;
right = out.size()-1;
while(left<right){
int mid = left+(right-left+1)/2;
if(out.get(mid)>=persons[i]){
right = mid-1;
}else{
left = mid;
}
}
if(out.get(left)<persons[i]){
cnt-=(left+1);
}
res[i] = cnt;
}
return res;
}
}