TwoSum Java code using HashMap


  • 30
    S
    public int[] twoSum(int[] nums, int target) {
         HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    		int[] defaultResult = {0, 0};
    		for (int i = 0; i < nums.length; i++) {
    			if (map.get(target-nums[i]) != null ) {
    				int[] result = {map.get(target-nums[i]) + 1, i + 1 };
    				return result;
    			}
    			map.put(nums[i], i);
    		}
    		return defaultResult;
        }

  • 0
    T

    00000000000000000


  • 1
    S

    can someone please explain the code.


Log in to reply
 

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