new group contact

http://www.1point3acres.com/bbs/thread-148422-1-1.html

http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=192328&extra=page%3D1%26filter%3Dsortid%26sortid%3D311%26searchoption%255B3046%255D%255Bvalue%255D%3D2%26searchoption%255B3046%255D%255Btype%255D%3Dradio&page=1

Contact Dedup, 输入是这样的:数字是用户,字母是邮箱,有很多人有多个邮箱,找出相同的用户
  1- {x,y,z},  
  2-{x} 
  3-{a,b}
  4-{y, z}
  5-{b}
  6-{m}
  7-{t,b}. visit 1point3acres.com for more.

这样输出就是 [1,2,4,7] [3,5] [6] 总共有三个用户。
可以用UnionFind或者Connected Components的方法做

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class NewGroupContact {
	public static void main(String[] args) {

		HashMap<String/* string value */, Integer/* type */> h = new HashMap<>();
		// String[][] A = { { "John", "john@gmail.com", "john@fb.com" },
		// { "Dan", "dan@gmail.com", "+1234567" },
		// { "john123", "+5412312", "john123@skype.com" },
		// { "john1985", "+5412312", "john@fb.com" },
		// { "Dan12", "+1234567", "dan@fb.com" },
		// { "Shaohui", "+4125194763", "sguo@fb.com" }};

		String[][] A = { { "x", "y", "z" }, { "x" }, { "a", "b" }, { "y", "z" }, { "m", "a" },
				{ "Shaohui", "+4125194763", "sguo@fb.com", "x" } };

		int code = 0;
		for (int i = 0; i < A.length; i++) {
			int c = -1;
			Set<Integer> groupings = new HashSet<Integer>();
			for (int j = 0; j < A[i].length; j++) {
				String s = A[i][j];
				if (h.containsKey(s)) {
					int value = h.get(s);
					groupings.add(value);
					c = Math.max(c, value);
				}
			}
			if (c == -1) {
				c = code++;
			} else {
				groupings.remove(c);
				for (Integer k : groupings) {
					for (int m = 0; m < A[0].length; m++) {
						h.put(A[k][m], c);
					}
				}

			}
			for (int j = 0; j < A[i].length; j++) {
				String s = A[i][j];
				h.put(s, c);
			}
		}

		for (int i = 0; i < A.length; i++) {
			System.out.println(h.get(A[i][0]));
		}
		Map<Integer/* type */, Set<String>> res = new HashMap<>();
		for (Map.Entry<String, Integer> entry : h.entrySet()) {
			if (res.containsKey(entry.getValue())) {
				Set<String> set = res.get(entry.getValue());
				set.add(entry.getKey());
			} else {
				Set<String> set = new HashSet<>();
				set.add(entry.getKey());
				res.put(entry.getValue(), set);
			}
		}
		for (Set<String> set: res.values()) {
			for (String s: set) {
				System.out.print(s + " ");
			}
			System.out.println("");
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值