Java clean & simple code with comments beats ~72%


  • 0
    S
    class Solution {
        public String[] findRestaurant(String[] list1, String[] list2) {
            // Set the rate to MAX_VALUE to compare against Andy & Dory ratings
            int rate = Integer.MAX_VALUE;
            // Holds the result
            List<String> matches = new ArrayList<String>();
            // Restaraunts and preference rate for Andy (list1)
            Map<String, Integer> map = new HashMap<String, Integer>();
            
            // Maps restaurant to its rating in the array (according to pos. in the array)
            for (int i = 0; i < list1.length; ++i) 
                map.put(list1[i], i);
            
            // Go through Doris (list2) preferences
            for (int i = 0; i < list2.length; ++i) {
                // Check if exists match to Andys list
                if (map.containsKey(list2[i])) {
                    // Combine rating of Andy + Doris
                    int compRate = i + map.get(list2[i]);
                    // If the rating is the same as previous(tie condition) add to the list
                    if (compRate == rate) matches.add(list2[i]);
                    // If the rating is smaller
                    if (compRate < rate) {
                        // Reset the result list
                        matches = new ArrayList<String>();
                        // Add new match
                        matches.add(list2[i]);
                        // Reset the rating to a new lower combination
                        rate = compRate;
                    }
                }
            }
            
            // Return result
            return matches.toArray(new String[0]);
        }
    }
    

Log in to reply
 

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