高级农民
- 积分
- 3790
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2009-8-10
- 最后登录
- 1970-1-1
|
本帖最后由 wengjn 于 2021-4-8 13:56 编辑
c# 实现了下
先通过union find来分组 然后一个个组打印出来就好了
- class HelloWorld {
- static void Main() {
- var test = new int[] { 4, 3, 7, 6, 9, 2 };
- int k = 1;
-
- var uf = new UnionFind(test.Length);
-
- for (int i=0; i<test.Length-1; i++) {
- for (int j=i+1; j<test.Length; j++) {
- if (NumsWithinRange(test[i], test[j], k)) {
- uf.Union(i, j);
- }
- }
- }
- var res = new Dictionary<int, IList<int>>();
-
- for (int i=0; i<test.Length; i++) {
- int groupNumber = uf.Find(i);
- if (!res.ContainsKey(groupNumber)) {
- res[groupNumber] = new List<int>();
- }
- res[groupNumber].Add(test[i]);
- }
-
- foreach (var ls in res) {
- Console.Write("\n");
- foreach (var item in ls.Value) {
- Console.Write(item + ", ");
- }
- }
-
- }
-
- public static bool NumsWithinRange(int x, int y, int range) {
- int diff = Math.Abs(x - y);
- return diff <= range;
- }
- }
- public class UnionFind {
- public int[] parent, rank;
- public int groups;
-
- public UnionFind(int n) {
- parent = new int[n];
- rank = new int[n];
- for (int i=0; i<n; i++) {
- parent[i] = i;
- }
- groups = n;
- }
-
- public void Union(int x, int y) {
- int px = Find(x);
- int py = Find(y);
- if (px == py) return;
-
- if (rank[px] > rank[py]) {
- parent[py] = px;
- rank[px]++;
- } else {
- parent[px] = py;
- rank[py]++;
- }
- groups--;
- }
-
- public int Find(int x) {
- while (parent[x] != x) {
- return Find(parent[x]);
- }
- return x;
- }
- }
复制代码 [/i][/i][/i] |
|