JAVA Easy Solution, Beat 90%


  • 0
    J
    public class Solution {
        public String[] findRestaurant(String[] list1, String[] list2) {
            if (list1 == null || list1.length == 0 || list2 == null || list2.length == 0) return new String[0];
            int len1 = list1.length, len2 = list2.length, min = Integer.MAX_VALUE;
            List<String> list = new ArrayList<>();
            HashMap<String, Integer> map = new HashMap<>();
            
            for (int i = 0; i < len1; i++) {
                map.put(list1[i], i);
            }
            
            for (int i = 0; i < len2; i++) {
                if (map.get(list2[i]) != null) {
                    int val = map.get(list2[i]);
                    if (min > val + i) {
                        list.clear();
                        min = i + val;
                        list.add(list2[i]);
                    } else if (min == val + i) {
                        list.add(list2[i]);
                    }
                }
            }
            
            String res[] = new String[list.size()];
            
            for (int i = 0; i < list.size(); i++) {
                res[i] = list.get(i);
            }
            
            return res;
        }
    }

Log in to reply
 

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