LeetCode Two Sum

Java HashMap 基本操作在这题里

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>(); // Constructor
        for(int i=nums.length-1; i>=0; i--){
            int adder = target-nums[i];
            if(map.containsKey(adder)){ // Check if map has the key
                return new int[] {i+1, map.get(adder)+1};  // Get the value from the key
            }
            else{
                map.put(nums[i], i);  // Add new key-value pair
            }
        }
        return new int[] {-1, -1};
    }
}