Two Sum
Given: Array of integers and a target Output: Find two indices where array elements sum is equals to target
Intuition: Use HashMaps in Java to simplify the solution, I check the difference of the target-current array element value in map and then check if the map already contains a key with difference. If yes, return the index of the difference element and current element in an integer array, else put the current element into map with index i.
Java Implementation
class Solution { public int[] twoSum(int[] nums, int target) { int solution[] = new int[2]; Mapmap = new HashMap<>(); for(int i=0;i < nums.length; i++){ int curr = nums[i]; int diff = target - curr; if(map.containsKey(diff)){ return new int[] {map.get(diff), i}; } map.put(curr, i); } return new int[] {0,0}; } }