57 ms, 在所有 Java 提交中击败了70.67%的用户
48.7 MB, 在所有 Java 提交中击败了89.04%的用户
数组替代队列,从超时到击败70%,用tree[0]替代new一个新的ArrayList,上升10%
思想是遍历一遍,删除度为1的节点,答案只可能为1或2
1 public List<Integer> findMinHeightTrees(int n, int[][] edges) { 2 ArrayList<Integer>[] tree = new ArrayList[n]; 3 for (int i = 0; i < n; i++) tree[i] = new ArrayList<>(); 4 for (int i = 0; i < edges.length; i++) { 5 int a = edges[i][0], b = edges[i][1]; 6 tree[a].add(b); 7 tree[b].add(a); 8 } 9 int[] valid = new int[n]; 10 Arrays.fill(valid, 1); 11 int[] q = new int[n]; 12 int len = n; 13 while (len > 2) { 14 q[0] = 0; 15 for (int i = 0; i < n; i++) if (tree[i].size() == 1) q[++q[0]] = i; 16 len -= q[0]; 17 for (int j = 1; j <= q[0]; j++) { 18 int a = q[j], b = tree[a].get(0); 19 tree[a].clear(); 20 for (int i = 0; i < tree[b].size(); i++) { 21 if (tree[b].get(i) == a) { 22 tree[b].remove(i); 23 break; 24 } 25 } 26 valid[a] = 0; 27 } 28 } 29 tree[0].clear(); 30 for (int i = 0; i < n; i++) if (valid[i] == 1) tree[0].add(i); 31 return tree[0]; 32 }