Java HashMap solution


  • 0
    A
    public class Solution {
        public String[] findRestaurant(String[] list1, String[] list2) {
            ArrayList<String> best = new ArrayList<>();
            int maxSum = Integer.MAX_VALUE;
            HashMap<String,Integer> map = new HashMap<>();
            
            for(int i = 0; i < list1.length; i++)
                map.put(list1[i],i);
            
            for(int i = 0; i < list2.length;i++)
            {
                if(map.containsKey(list2[i]))
                {
                    int index = map.get(list2[i]) + i;
                    if(index == maxSum)
                        best.add(list2[i]);
                    else if(index < maxSum)
                    {
                        best = new ArrayList<>();
                        best.add(list2[i]);
                        maxSum = index;
                    }
                }
            }
            
            return best.toArray(new String[best.size()]);
        }
    }
    

Log in to reply
 

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