提交 9e6859a6 编写于 作者: L liu13

20190507

上级 15e0467a
package code;
/*
* 343. Integer Break
* 题意:给定一个正整数,找出一组数字和为该数,且这组数的乘积最大
* 难度:Medium
* 分类:Math, Dynamic Programming
* 思路:能减3的减3,因为3得到的乘积最大
* Tips:
*/
public class lc343 {
public int integerBreak(int n) {
if(n==2) return 1;
if(n==3) return 2;
return helper(n);
}
public int helper(int n){
if(n==2) return 2;
if(n==3) return 3;
if(n==4) return 4;
if(n==5) return 6;
else return helper(n-3)*3;
}
}
package code;
/*
* 685. Redundant Connection II
* 题意:一个图,删掉一个边,使其成为一个根树
* 难度:Hard
* 分类:Tree, Depth-first Search, Union Find, Graph
* 思路:要把问题想清楚
* 判断是否有某个节点父节点有两个, 记为e1, e2
* 再判断是否有环
* 4中情况,分别想清楚返回什么
* 自己没想清楚两种情况的交叉,以为判断完第一步就可直接返回
* 如何判断有环,可以利用并查集的思想
* Tips:https://leetcode.com/problems/redundant-connection-ii/discuss/108045/C%2B%2BJava-Union-Find-with-explanation-O(n)
*/
public class lc685 {
public int[] findRedundantDirectedConnection(int[][] edges) {
int[] can1 = {-1, -1};
int[] can2 = {-1, -1};
int[] parent = new int[edges.length + 1];
for (int i = 0; i < edges.length; i++) {
if (parent[edges[i][1]] == 0) {
parent[edges[i][1]] = edges[i][0];
} else {
can2 = new int[] {edges[i][0], edges[i][1]};
can1 = new int[] {parent[edges[i][1]], edges[i][1]};
edges[i][1] = 0;
}
}
for (int i = 0; i < edges.length; i++) {
parent[i] = i;
}
for (int i = 0; i < edges.length; i++) {
if (edges[i][1] == 0) {
continue;
}
int child = edges[i][1], father = edges[i][0];
if (root(parent, father) == child) { //判断father的父节点是不是child
if (can1[0] == -1) {
return edges[i];
}
return can1;
}
parent[child] = father;
}
return can2;
}
int root(int[] parent, int i) {
while (i != parent[i]) { //找到根为止
parent[i] = parent[parent[i]];
i = parent[i];
}
return i;
}
}
......@@ -190,7 +190,8 @@ LeetCode 指南
| 337 [Java](./code/lc337.java)
| 338 [Java](./code/lc338.java)
| 341 [Java](./code/lc341.java)
| 344 [Java](./code/lc338.java)
| 343 [Java](./code/lc343.java)
| 344 [Java](./code/lc344.java)
| 347 [Java](./code/lc347.java)
| 350 [Java](./code/lc350.java)
| 371 [Java](./code/lc371.java)
......@@ -217,6 +218,7 @@ LeetCode 指南
| 617 [Java](./code/lc617.java)
| 621 [Java](./code/lc621.java)
| 647 [Java](./code/lc647.java)
| 685 [Java](./code/lc685.java)
| 714 [Java](./code/lc714.java)
| 746 [Java](./code/lc746.java)
| 771 [Java](./code/lc771.java)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册