Java HashMap Solution, 26ms


  • 0
    F
    public String[] findRestaurant(String[] list1, String[] list2) {
    	Map<String, Integer> map = new HashMap<>();
    
    	List<String> res = new ArrayList<>();
    	int min = Integer.MAX_VALUE;
    
    	for (int i = 0; i < list1.length; i++) {
    		map.put(list1[i], i);
    	}
    
    	for (int j = 0; j < list2.length; j++) {
    		if (map.containsKey(list2[j])) {
    			int sum = map.get(list2[j]) + j;
    			if (sum == min) {
    				res.add(list2[j]);
    			} else if (sum < min) {
    				res.clear();
    				res.add(list2[j]);
    				min = sum;
    			}
    		}
    	}
    
    	return res.toArray(new String[0]);
    }

Log in to reply
 

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