One pass hashtable question


  • 0
    M

    Why does this work:

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
            for (int i = 0; i < nums.length; i++) {
                int match = target - nums[i];
                if (map.containsKey(match)) {
                    return new int[]{map.get(match), i};
                }
                map.put(nums[i], i);
            }
            throw new IllegalArgumentException("no two num solution");
        }
    }
    

    But not if I change it to put match in the map and check if the map contains nums[i] like so:

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
            for (int i = 0; i < nums.length; i++) {
                int match = target - nums[i];
                if (map.containsKey(nums[i])) {
                    return new int[]{map.get(match), i};
                }
                map.put(match, i);
            }
            throw new IllegalArgumentException("no two num solution");
        }
    }
    

Log in to reply
 

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