HashMap Solution Java


  • 0
    N
        public String[] findRestaurant(String[] list1, String[] list2) {
           
           int l1=list1.length,l2=list2.length,sum=Integer.MAX_VALUE;
            HashMap<String,Integer> list = new HashMap();
            
            for(int i=0;i<l1;++i)
                list.put(list1[i],new Integer(i));
            
             ArrayList<String> res = new ArrayList();
          
            for(int i=0;i<l2;++i){
                int j=list.get(list2[i])!=null?list.get(list2[i]):-1;
                if(j>=0){
                   if(sum==Integer.MAX_VALUE||sum>i+j){
                       res.clear();
                       res.add(list2[i]);
                      sum=i+j;
                   }else if(min==sum){
                        res.add(list2[i]);
                   }
                }
            }
        
            String[] result = new String[res.size()];
            for(int i=0;i<res.size();++i)
                    result[i]=res.get(i);
            
           return result; 
        }
    }

Log in to reply
 

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