Java Solution with Comments


  • 12
    C
    public int[] twoSum(int[] nums, int target){
    	int[] result = {0,0}; //initialized ther result
    	Map<Integer, Integer> map = new HashMap<>();
    	/*
    	 * for every entry in the array, store the (target-num) into the map with the index of the num
    	 * When the (target- num)appears in the array, we can return the values at that moment itself
    	 */
    	for(int i=0; i<nums.length; i++){
    		if(map.containsKey(nums[i])){
    			result[0] = map.get(nums[i]);
    			result[1] = map.get(i);
    			return result;
    		}else{
    			map.put(target-nums[i], i);
    		}
    	}
    	return result;
    }

  • 7
    L
     result[0] = map.get(nums[i])+1;
            result[1] = i+1;

  • 0
    Z

    result[1] = map.get(i);
    change to:
    result[1]=i;


  • 1
    R

    result[0] = map.get(nums[i]);
    result[1] = i;
    I have run it on eclipse.


  • 0
    W
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>(nums.length << 1);
        for (int i = 0, j = target - nums[0];; map.put(nums[i], i), j = target - nums[++i])
            if (map.containsKey(j)) return new int[] { map.get(j), i };
    }
    

    you can code like this


Log in to reply
 

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