Wednesday, May 3, 2017

LeetCode 2nd time 1. Two sum leetcode Java

   public int[] twoSum(int[] nums, int target) {  
     if(nums==null || nums.length<2) {  
      throw new IllegalArgumentException("No two sum solution");   
     }  
     Map<Integer,Integer> helper=new HashMap<Integer,Integer>();  
     for(int i=0;i<nums.length;i++){  
       if(helper.containsKey(target-nums[i])){  
       return new int[]{helper.get(target-nums[i]),i};  
       }  
       else{  
         helper.put(nums[i],i);  
       }  
     }  
      throw new IllegalArgumentException("No two sum solution");  
   }  

No comments:

Post a Comment