Minimum Index Sum of Two Lists

https://www.lintcode.com/problem/minimum-index-sum-of-two-lists/description

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Solution {
    /**
     * @param list1: a list of strings
     * @param list2: a list of strings
     * @return: the common interest with the least list index sum
     */
    public String[] findRestaurant(String[] list1, String[] list2) {
        // Write your code here
        Map map1 = new HashMap<>();
        Map map2 = new HashMap<>();
        Map map = new HashMap<>();
        for (int i = 0; i < list1.length; i++) {
            String s = list1[i];
            map1.put(s, i);
        }
        for (int i = 0; i < list2.length; i++) {
            String s = list2[i];
            map2.put(s, i);
        }
        Iterator iterator = map1.keySet().iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            Integer integer = map2.get(next);
            if (integer != null) {
                map.put(next, map1.get(next) + integer);
            }
        }
        Set> entries = map.entrySet();
        List> list = new ArrayList<>(entries);
        Collections.sort(list, new Comparator>() {
            @Override
            public int compare(Map.Entry o1, Map.Entry o2) {
                return o1.getValue() - o2.getValue();
            }
        });
        System.out.println("list=" + list);
        List res = new ArrayList<>();
        res.add(list.get(0).getKey());
        for (int i = 1; i < list.size(); i++) {
            Map.Entry entry = list.get(i);
            if (list.get(i - 1).getValue().intValue() == entry.getValue().intValue()) {
                res.add(entry.getKey());
            } else {
                break;
            }
        }
        System.out.println("res=" + res);
        String[] temp = new String[res.size()];
        res.toArray(temp);
        return temp;
    }
}

你可能感兴趣的:(Minimum Index Sum of Two Lists)