9 lines of code: alternative thought using Lambda Expression and TreeMap


  • 0
    Y

    Using use tree.compute and Lambda Expression to add any qualified matched restaurants into a treemap.
    A treemap is sorted by using tree.firstEntry() to get the least index sum.

    class Solution {
        public String[] findRestaurant(String[] list1, String[] list2) {
            TreeMap<Integer, String> tree = new TreeMap<Integer, String>();
            HashMap<String, Integer> map = new HashMap<String, Integer>();
            
            for (int i = 0; i < list1.length; i++)
                map.put(list1[i], i);
            
            for (int i = 0; i < list2.length; i++) {
                String s = list2[i];
                if(map.containsKey(s))
                    tree.compute(map.get(s) + i, (a, b) -> b == null? s: b + ", " + s);
            }
            
            return tree.firstEntry().getValue().split(", ");
            
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.