Java solution with hashmap


  • 0
    F
    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            
            int[] result = null;
    		
    		Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
    		int index = 1; 
    		for(int item : numbers){
    			
    			int expected = target - item; 
    			
    			if(map.containsKey(expected)){
    				result = new int[2];
    				result[0] = map.get(expected);
    				result[1] = index; 
    				break; 
    			}
    			
    			map.put(item, index++);
    		}
    		
    		return result;
        }
    }

Log in to reply
 

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