Short Java solution WITHOUT HashMap


  • 0
    T

    The idea is to search the sum of the 2 index from 0 up to list1.length + list2.length - 2. If we find matches, we can stop right away:

        public String[] findRestaurant(String[] list1, String[] list2) {
            int n = list1.length, m = list2.length;
            List<String> ans = new ArrayList<>();
            for (int sum = 0; ans.size() == 0; sum++) // since it is guaranteed to have an answer, "ans.size() == 0" will break for sure. 
                for (int i = Math.max(0, sum - m + 1); i <= Math.min(n - 1, sum); i++)
                    if (list1[i].equals(list2[sum - i])) ans.add(list1[i]);
            return ans.toArray(new String[ans.size()]);
        }
    

Log in to reply
 

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