AC第六天

1. 统计被覆盖的建筑 LeetCode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class LeetCodeTest {
@Test
public void test() {
int n = 5;
int[][] buildings = {{1, 3}, {3, 2}, {3, 3}, {3, 5}, {5, 3}};
System.out.println(countCoveredBuildings(n, buildings));
}

public int countCoveredBuildings(int n, int[][] buildings) {
Map<Integer, int[]> rowMinMax = new HashMap<>();
Map<Integer, int[]> colMinMax = new HashMap<>();
for (int[] building : buildings) {
int x = building[0], y = building[1];
rowMinMax.compute(x, (k, v) -> v == null ? new int[]{y, y} : new int[]{Math.min(v[0], y), Math.max(v[1], y)});
colMinMax.compute(y, (k, v) -> v == null ? new int[]{x, x} : new int[]{Math.min(v[0], x), Math.max(v[1], x)});
}

int ans = 0;
for (int[] p : buildings) {
int x = p[0], y = p[1];
int[] row = rowMinMax.get(x);
int[] col = colMinMax.get(y);
if (row[0] < y && y < row[1] && col[0] < x && x < col[1]) {
ans++;
}
}
return ans;
}
}

思路: 按行和列分别求出存在的最小值和最大值作为边界,在这个边界内查找,只要有符合条件的建筑就计数+1。

2. 平衡二叉树 LeetCode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class LeetCodeTest {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}

@Test
public void test() {
TreeNode root = new TreeNode(3,
new TreeNode(9),
new TreeNode(20, new TreeNode(15), new TreeNode(7))
);
System.out.println(isBalanced(root));
}

public boolean isBalanced(TreeNode root) {
return height(root) != -1;
}

private int height(TreeNode node) {
if (node == null) return 0;
int leftHeight = height(node.left);
if (leftHeight == -1) return -1;
int rightHeight = height(node.right);
if (rightHeight == -1) return -1;
if (Math.abs(leftHeight - rightHeight) > 1) return -1;
return Math.max(leftHeight,rightHeight) + 1;
}
}

思路: 这道题主要考察对平衡二叉树的理解。

1. 定义

平衡二叉树(Balanced Binary Tree)又被称为AVL树。它具有以下性质:
它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树

平衡二叉树一般是一个有序树,它具有二叉树的所有性质,其遍历操作和二叉树的遍历操作相同。但是由于其对二叉树施加了额外限制,因而其添加、删除操作都必须保证平衡二叉树的因子被保持。

平衡二叉树中引入了一个概念:平衡二叉树节点的平衡因子,它指的是该节点的两个子树,即左子树和右子树的高度差,即用左子树的高度减去右子树的高度。如果该节点的某个子树不存在,则该子树的高度为0。如果高度差的绝对值超过1,就要根据情况进行调整

2. 平衡

平衡的调整共有四种情况:分别为 LL、LR、RR、RL。

  • LL(左左):右旋调整。
  • LR(左右):先左旋,再右旋调整。
  • RR(右右):左旋调整。
  • RL(右左):先右旋,再左旋调整。

具体文档参考自:CSDN