Java single HashMap w/o keep refreshing output list


  • 0
    O

    Negative index stored in map indicates string no match in list2.

    public class Solution {
        public String[] findRestaurant(String[] list1, String[] list2) {
            Map<String, Integer> m = new HashMap<>();
            List<String> ans = new ArrayList<>();
            Integer min = Integer.MAX_VALUE;
            
            // 1. Put all list1's strings into map with negative index 
            for(int i = 0; i < list1.length; i++) {
                m.put(list1[i], -i);
            }
            
            // 2. If string exists in map then replace it with index sum
            for(int i = 0; i < list2.length; i++) {
                Integer v = m.get(list2[i]);
                if(v != null) {
                    v = Math.abs(v) + i;
                    m.put(list2[i], v);
                    min = Math.min(min, v);
                }
            }
    
            // 3. Add all strings with minimum value into output
            for(Map.Entry<String, Integer> e : m.entrySet()) {
                // value negative will take effect here
                if(min.equals(e.getValue())) {
                    ans.add(e.getKey());
                }
            }
            
            return ans.toArray(new String[0]);
        }
    }
    

Log in to reply
 

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