Two Sum

Run Settings
LanguageJava
Language Version
Run Command
import java.util.*; class Main { /* Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. nums = [2, 7, 11, 15] target = 9 output = [0, 1] // create a HashMap to store the numbers // iterate through the array and check if the complement exits // return the current element, otherwise its index //if solution found, return empty array */ // time and space : o(n) public static int[] twoSum(int[]nums, int target){ HashMap<Integer, Integer>map = new HashMap<>(); for (int i=0; i<nums.length; i++){ int complement = target -nums[i]; if (map.containsKey(complement)){ return new int[]{map.get(complement), i}; } map.put(nums[i], i); } return new int[0]; } public static void main(String[] args) { int[] nums = {2, 7, 11, 15}; int target = 9; int[] result = twoSum(nums, target); System.out.print(Arrays.toString(result)); } }
Editor Settings
Theme
Key bindings
Full width
Lines