题目:
https://leetcode-cn.com/problems/falling-squares/submissions/
我的代码不快,但也不至于超时,但是容易理解
每个新的格子进来,与之前的格子进行比较,找到最大值
代码:
public List<Integer> fallingSquares(int[][] positions) {
List<Integer> ans = new ArrayList<>();
int len = positions.length;
Map<int[], Integer> map = new HashMap<>();
int anss = 0;
for (int i = 0; i < len; i++) {
anss = Math.max(getAns(positions[i], map),anss);
ans.add(anss);
}
return ans;
}
//找到本正方形的最高点
private int getAns(int[] position, Map<int[], Integer> map) {
int ans = position[1];
int h = position[1];
//格子的右边界
position[1] = position[0] + position[1];
Set<int[]> set = map.keySet();
//因为发现有覆盖,旧的要删除,所以使用迭代器
Iterator<int[]> iterator = set.iterator();
while(iterator.hasNext()){
int[] key = iterator.next();
//判断新格子与旧格子的关系
int point = getpoint(key, position);
if (point == 0) {
//没有交集就结束
continue;
}
int v = map.get(key);
if (point == 2) {
iterator.remove();
}
ans = Math.max(v + h, ans);
}
map.put(position, ans);
return ans;
}
private int getpoint(int[] key, int[] position) {
//新的能覆盖旧的
if (position[0] <= key[0] && position[1] >= key[1]) {
return 2;
}
//新的和旧的没有交集
if (position[0] >= key[1] || position[1] <= key[0]) {
return 0;
}
//有交集
return 1;
}