Is it JAVA O(n) solution?


  • 0
    A
    import java.util.HashMap;
    
    class Solution {
        public String[] findRestaurant(String[] list1, String[] list2) {
            int len1 = list1.length, len2 = list2.length, i = 0, j = 0, val = 0, temp = Integer.MAX_VALUE;
            Map<String,Integer> hash = new HashMap<>();
            ArrayList<String> result = new ArrayList<>();
            
            while(i != len1 || j != len2){
                if(i != len1){
                    if(hash.containsKey(list1[i])){
                        val = (int) hash.get(list1[i]) + i;
                        if(val < temp){
                            temp = val;
                            result.add(list1[i]);
                            System.out.println(list1[i]);
                        }else if(val == temp){
                            result.add(list1[i]);
                        }
                    }else{
                        hash.put(list1[i],i);
                    }
                    i++;
                }
                if(j != len2){
                    if(hash.containsKey(list2[j])){
                        val = (int) hash.get(list2[j]) + j;
                        if(val < temp){
                            temp = val;
                            result.add(list2[j]);
                        }else if(val == temp){
                            result.add(list2[j]);
                        }
                    }else{
                        hash.put(list2[j],j);
                    }
                    j++;
                }
            }
            return result.toArray(new String[result.size()]);
        }
    }
    

Log in to reply
 

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