中级农民
- 积分
- 155
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-4-17
- 最后登录
- 1970-1-1
|
写了下第三题java版,感觉它们加系统设计真多啊
- public class GroupContacts {
- static class Contact {
- String name;
- List<String> emails;
- public Contact(String name, List<String> emails) {
- this.name = name;
- this.emails = emails;
- }
- }
- static class UnionFind {
- HashMap<Integer, Integer> father = new HashMap<Integer, Integer>();
- UnionFind(int n) {
- for (int i = 0; i < n; i++) {
- father.put(i, i);
- }
- }
- int compressed_find(int x) {
- int parent = father.get(x);
- while (parent != father.get(parent)) {
- parent = father.get(parent);
- }
- int tmp = -1;
- int fa = father.get(x);
- while (fa != father.get(fa)) {
- tmp = father.get(fa);
- father.put(fa, parent);
- fa = tmp;
- }
- return parent;
- }
- int find(int id) {
- while (id != father.get(id)) {
- id = father.get(id);
- }
- return id;
- }
- void union(int x, int y) {
- int fa_x = compressed_find(x);
- int fa_y = compressed_find(y);
- father.put(fa_x, fa_y);
- }
- }
- public static List<List<Contact>> groupContacts(Contact[] input) {
- Map<String, List<Integer>> emailRecord = new HashMap<String, List<Integer>>();
- int n = input.length;
- for (int k = 0; k < input.length; k++) {
- for (String email : input[k].emails) {
- if (emailRecord.containsKey(email)) {
- emailRecord.get(email).add(k);
- } else {
- List<Integer> list = new ArrayList<Integer>();
- list.add(k);
- emailRecord.put(email, list);
- }
- }
- }
- UnionFind uf = new UnionFind(n);
- for (List<Integer> p : emailRecord.values()) {
- for (int i = 0; i < p.size() - 1; i++) {
- uf.union(p.get(i), p.get(i + 1));
- }
- }
- Map<Integer, List<Integer>> groups = new HashMap<Integer, List<Integer>>();
- for (int i = 0; i < n; i++) {
- int parent = uf.find(i);
- if (groups.containsKey(parent)) {
- groups.get(parent).add(i);
- } else {
- List<Integer> list = new ArrayList<Integer>();
- list.add(i);
- groups.put(parent, list);
- }
- }
- List<List<Contact>> ret = new ArrayList<List<Contact>>();
- for (List<Integer> p : groups.values()) {
- List<Contact> vs = new ArrayList<Contact>();
- for (int c : p) {
- vs.add(input[c]);
- }
- ret.add(vs);
- }
- return ret;
- }
-
- public static void main(String[] args) {
- Contact c1 = new Contact("John", Arrays.asList("john@gmail.com"));
- Contact c2 = new Contact("Mary", Arrays.asList("mary@gmail.com"));
- Contact c3 = new Contact("John", Arrays.asList("john@yahoo.com"));
- Contact c4 = new Contact("John", Arrays.asList("john@gmail.com", "john@yahoo.com", "john@hotmail.com"));
- Contact c5 = new Contact("Bob", Arrays.asList("bob@gmail.com"));
- Contact[] input = {c1, c2, c3, c4, c5};
- List<List<Contact>> res = groupContacts(input);
- for (List<Contact> list : res) {
- for (Contact i : list) {
- System.out.print(i.name + ": ");
- for (String email : i.emails) {
- System.out.print(email + " ");
- }
- }
- System.out.println();
- }
- }
- }
复制代码 |
|