- 浏览: 130503 次
文章分类
- 全部博客 (189)
- Tree (14)
- Dynamic Programming (34)
- Array (20)
- Search (1)
- Hash (12)
- Backtracking (22)
- Divide and Conque (8)
- Greedy (6)
- Stack (12)
- software (0)
- List (7)
- Math (22)
- Two pointers (16)
- String (20)
- Linux (1)
- Sliding Window (4)
- Finite State Machine (1)
- Breadth-first Search (7)
- Graph (4)
- DFS (6)
- BFS (3)
- Sort (9)
- 基础概念 (2)
- 沟通表达 (0)
- Heap (2)
- Binary Search (15)
- 小结 (1)
- Bit Manipulation (8)
- Union Find (4)
- Topological Sort (1)
- PriorityQueue (1)
- Design Pattern (1)
- Design (1)
- Iterator (1)
- Queue (1)
最新评论
-
likesky3:
看了数据结构书得知并不是迭代和递归的区别,yb君的写法的效果是 ...
Leetcode - Graph Valid Tree -
likesky3:
迭代和递归的区别吧~
Leetcode - Graph Valid Tree -
qb_2008:
还有一种find写法:int find(int p) { i ...
Leetcode - Graph Valid Tree -
qb_2008:
要看懂这些技巧的代码确实比较困难。我是这么看懂的:1. 明白这 ...
Leetcode - Single Num II -
qb_2008:
public int singleNumber2(int[] ...
Leetcode - Single Num II
Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
For example:
Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.
Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.
Show Hint
Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
[分析]
应用Union Find算法的好例子,对Union Find算法不熟悉,可参看
http://blog.csdn.net/dm_vincent/article/details/7655764
http://blog.csdn.net/dm_vincent/article/details/7769159
个人觉得该博文阐述非常通俗易懂,第二个链接是博主举的几个应用例子。
对这题依次实现了不同优化程度的union find算法,从运行时间可看出优化是很有效果的。
第二部分代码是利用教材中的UnionFind算法实现,实现中包含路径压缩和按大小以及按秩(rank)求并思想,且仅需要一个数组s[],初始时s[i] = -1, 在合并过程中根的s[]值是该根所对应树的size的相反数,而非根节点的s[]指向其父节点。每次find一个节点p会将p到根上的所有节点的父节点均置为根,从而高效压缩路径。利用unionFind求解该题时,需要稍修改union,union函数返回值改为布尔类型,union时,若发现两个节点已在同一颗树中,即root相同,说明该条边会使得树中产生一个cycle,返回false,说明输入并非valid tree。全部边顺利union结束还不能说明输入是valid tree,验证union后有且仅有一个根方能确认输入是valid tree。
优化的union可以按大小也可以按高度合并,因为路径压缩过程会改变树的高度,所以其与按高度求并并不完全兼容,书中提到目前并不清楚这种情况下如何有效重新计算高度,答案是不去计算,就让每棵树存储的高度是估计的高度(rank),理论上证明按秩求并和按大小求并效率是一样的,且高度的更新不如大小更新频繁。
For example:
Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.
Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.
Show Hint
Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
[分析]
应用Union Find算法的好例子,对Union Find算法不熟悉,可参看
http://blog.csdn.net/dm_vincent/article/details/7655764
http://blog.csdn.net/dm_vincent/article/details/7769159
个人觉得该博文阐述非常通俗易懂,第二个链接是博主举的几个应用例子。
对这题依次实现了不同优化程度的union find算法,从运行时间可看出优化是很有效果的。
第二部分代码是利用教材中的UnionFind算法实现,实现中包含路径压缩和按大小以及按秩(rank)求并思想,且仅需要一个数组s[],初始时s[i] = -1, 在合并过程中根的s[]值是该根所对应树的size的相反数,而非根节点的s[]指向其父节点。每次find一个节点p会将p到根上的所有节点的父节点均置为根,从而高效压缩路径。利用unionFind求解该题时,需要稍修改union,union函数返回值改为布尔类型,union时,若发现两个节点已在同一颗树中,即root相同,说明该条边会使得树中产生一个cycle,返回false,说明输入并非valid tree。全部边顺利union结束还不能说明输入是valid tree,验证union后有且仅有一个根方能确认输入是valid tree。
优化的union可以按大小也可以按高度合并,因为路径压缩过程会改变树的高度,所以其与按高度求并并不完全兼容,书中提到目前并不清楚这种情况下如何有效重新计算高度,答案是不去计算,就让每棵树存储的高度是估计的高度(rank),理论上证明按秩求并和按大小求并效率是一样的,且高度的更新不如大小更新频繁。
public class Solution { // http://blog.csdn.net/dm_vincent/article/details/7655764 int count = 0; int[] id = null; int[] size = null; public boolean validTree(int n, int[][] edges) { initUnionFind(n); for (int i = 0; i < edges.length; i++) { int p = edges[i][0], q = edges[i][1]; if (find(p) == find(q)) return false; union(p, q); } return count == 1 ? true : false; } public void initUnionFind(int n) { id = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { id[i] = i; size[i] = 1; } count = n; } //version 4: weighted quick union with path compression, find & union, very close to O(1) public int find(int p) { while (p != id[p]) { id[p] = id[id[p]]; p = id[p]; } return p; } public void union(int p, int q) { //same with version 3 int pRoot = find(p), qRoot = find(q); if (size[pRoot] < size[qRoot]) { id[pRoot] = qRoot; size[qRoot] += size[pRoot]; } else { id[qRoot] = pRoot; size[pRoot] += size[qRoot]; } count--; } //version 3: weighted quick union, find & union, O(logn) public int find3(int p) { // same with version 2 while (p != id[p]) p = id[p]; return p; } public void union3(int p, int q) { int pRoot = find(p), qRoot = find(q); if (size[pRoot] < size[qRoot]) { id[pRoot] = qRoot; size[qRoot] += size[pRoot]; } else { id[qRoot] = pRoot; size[pRoot] += size[qRoot]; } count--; } // version 2: quick union, find & union, O(tree height) public int find2(int p) { while (p != id[p]) p = id[p]; return p; } public void union2(int p, int q) { int pRoot = find(p), qRoot = find(q); id[pRoot] = qRoot; count--; } // version 1: quick find, find O(1), union O(n) public int find1(int p) { return id[p]; } public void union1(int p, int q) { int pId = find(p), qId = find(q);// 特别注意进入循环先保存原始值,循环过程id[p]会被更改 for (int i = 0; i < id.length; i++) { if (id[i] == pId) id[i] = qId; } count--; } }
public boolean validTree(int n, int[][] edges) { initUnionFind(n); for (int i = 0; i < edges.length; i++) { if (!union(edges[i][0], edges[i][1])) return false; } int count = 0; for (int i = 0; i < n; i++) { if (s[i] < 0) { count++; } } return count == 1; } private int[] s; private int count; public void initUnionFind(int n) { s = new int[n]; for (int i = 0; i < n; i++) s[i] = -1; } public int find(int p) { if (s[p] < 0) return p; else { s[p] = find(s[p]); return s[p]; } } // union by rank public boolean union(int p, int q) { int pRoot = find(p), qRoot = find(q); if (pRoot == qRoot) return false; if (s[pRoot] < s[qRoot]) { s[qRoot] = pRoot; } else { if (s[pRoot] == s[qRoot]) s[qRoot]--; s[pRoot] = qRoot; } return true; } // union by size public boolean union1(int p, int q) { int pRoot = find(p), qRoot = find(q); if (pRoot == qRoot) return false; if (s[pRoot] < s[qRoot]) { s[pRoot] += s[qRoot]; s[qRoot] = pRoot; } else { s[qRoot] += s[pRoot]; s[pRoot] = qRoot; } return true; }
评论
3 楼
likesky3
2015-09-21
看了数据结构书得知并不是迭代和递归的区别,yb君的写法的效果是从p到根的路径上每个节点都将根设为父节点,而我的写法效果是从p到根路径上每隔一个节点重置爷爷节点为父节点,压缩力度没有书上标准写法大,当然标准写法会多些递归开销。
2 楼
likesky3
2015-09-03
迭代和递归的区别吧~
1 楼
qb_2008
2015-09-02
还有一种find写法:
int find(int p) {
if (id[p] == p) {
return p;
}
return id[p] = find(id[p]);
}
int find(int p) {
if (id[p] == p) {
return p;
}
return id[p] = find(id[p]);
}
发表评论
-
Inorder Successor in BST
2015-09-26 17:49 688[分析] 参考https://leetcode.com/dis ... -
Lowest Common Ancestor of A Binary Tree
2015-09-26 11:39 534[分析] 最近公共祖先(LCA)是一个经典问题,以前没有好好 ... -
Leetcode - Closest Binary Search Tree Value II
2015-09-13 14:16 747[分析] 思路1:遍历所有节点找到和 target最接近的 k ... -
Leetcode - Surrounded Regions
2015-09-02 13:41 2654[分析] 思路1:和Number of Islands类似,但 ... -
Leetcode - Number of Islands
2015-09-02 09:40 2896[分析] BFS & DFS法详见实现。 这里阐述下u ... -
Leetcode - Closest Binary Search Tree Value II
2015-09-01 09:50 3140Given a non-empty binary search ... -
Leetcode - Binary Tree Upside Down
2015-08-29 18:50 383Given a binary tree where all t ... -
Leetcode - Verify Preorder Sequence in Binary Search Tree
2015-08-29 16:46 2998[分析] 思路1:暴力法,遍历当前待检查数组,找到第一个大于数 ... -
Leetcode - Converted Sorted List to BST
2015-08-23 20:07 324Given a singly linked list wher ... -
Leetcode - Kth Smallest Element in BST
2015-08-11 10:26 618[分析] 思路1: 递归中序遍历,返回中序遍历中的第k个数。 ... -
Leetcode - Recover Binary Search Tree
2015-07-02 09:27 493Two elements of a binary search ... -
Leetcode - Validate Binary Search Tree
2015-07-01 08:31 563Given a binary tree, determine ... -
Leetcode - Count Complete Tree Nodes
2015-06-07 20:51 740Definition of a complete binary ... -
Leetcode - Contains Duplicate III
2015-06-07 20:08 472Given an array of integers, fi ... -
MockInterview-FindNextValue
2015-04-12 08:57 0[题目] Return the next elemen ... -
MockInterview-Implement Dictionary
2015-04-12 08:56 0[题目] Implement a dictionary, s ... -
Leetcode - Unique Binary Search Trees
2015-04-10 10:00 536[题目] Given n, how many struc ...
相关推荐
leetcode-tag-Tree
《leetcode-solutions》,刷算法题,需要有一定的英文阅读能力。。。
IDEA 插件,lettcode刷题,leetcode-editor7.4版本下载进行本地导入(直接将压缩包拖进IDEA即可)
Algorithm-LeetCode-Sol-Res.zip,干净,易懂的解决方案和资源,为leetcode在线判断算法问题。,算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。
Algorithm-leetcode-spider.zip,leetcode公司,算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。
leetcode-cli-plugins leetcode-cli 的第 3 方插件。 什么是 如何使用 如何使用 插件 名称 描述 增强的命令 按公司或标签过滤问题 list 不要在同一台计算机上使 Chrome 的会话过期 login 不要在同一台计算机上使 ...
在IDE中解决LeetCode问题,支持leetcode.com与leetcode-cn.com,满足基本的做题需求。 理论上支持: IntelliJ IDEA PhpStorm WebStorm PyCharm RubyMine AppCode CLion GoLand DataGrip Rider MPS Android Studio。
解题思路思路和LeetCode-python 503.下一个更大元素 II一致,只是这里求的是下标的距离,而不是数值倒序搜索,用到栈,栈里存储索引情况1:若栈为
leetcode-cheat 的发布 它是什么 ? 这是一个chrome 扩展,可以帮助您更高效地使用 leetcode。您可以从 重要: leetcode-cheat 现在只支持中文版。 也就是说不完全支持leetcode.com,但是你可以用leetcode-cn.com代替...
leetcode 答案解析 golang解答
~/.vscode/extensions/leetcode.vscode-leetcode-0.17.0/node_modules/vsc-leetcode-cli/bin/leetcode /usr/local/bin/leetcode 修改模板 open ~/.vscode/extensions/leetcode.vscode-leetcode-0.17.0/node_modules/...
leetcode-editor,在ide中做leetcode练习,支持leetcode.com和leetcode-cn.com,以满足练习的基本需求。理论上支持:intellij idea phpstorm webstorm pycharm rubymine appcode clion goland datagrip rider mps ...
leetcode-helper-1.7.1
leetcode-tag-dynamic programming
然后进入到LeetCode-Spider目录中修改config.json,其中outputDir需要填写该工程的/docs/views文件夹路径 { "username": "aaa", "password": "bbb", "outputDir": "/Users/liuyao/Downloads/LeetCode-Blog-Test/docs...
leetcode-cli 注意:这个存储库是为了临时使用而分叉的。 注意:从 webbrowser 复制 cookie 并使用leetcode user -c可以临时修复不能。 一个享受 leetcode 的高效 cli 工具! 非常感谢 leetcode.com,一个非常棒的...
leetcode-tag-Stack
leetcode-tag-array
Algorithm-LeetCode-Solution-From-GuaZiDou.zip,Leetcode解决方案Gitbook,算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。