Two Sum Problem
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.
Example 1:
Input: nums = [2,7,11,15], target = 26
Output: [2,3]
Output: Because nums[2] + nums[3] == 26, we return [2, 3].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Method 1 : Brute force(Loop)
package bracecoder; import java.util.Scanner; public class TwoSum { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan=new Scanner(System.in); System.out.println("Enter number of count: "); int n=scan.nextInt(); int[] nums=new int[n]; System.out.println("Enter the number one by one: "); for(int i=0;i<n;i++) { nums[i]=scan.nextInt(); } System.out.println("Enter target value: "); int target=scan.nextInt(); int[] result=twoSum(nums,target); System.out.println(nums[result[0]]+"+"+nums[result[1]]+"="+target); } private static int[] twoSum(int[] nums, int target) { // TODO Auto-generated method stub for(int i=0;i<nums.length;i++) { for(int j=i+1;j<nums.length;j++) { if(nums[j]==target-nums[i]) { return new int[]{i,j}; } } } throw new IllegalArgumentException("No Two sum solution"); } }
OUTPUT
Method 2 : Hashmap
package bracecoder; import java.util.HashMap; import java.util.Scanner; public class TwoSum2 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan=new Scanner(System.in); System.out.println("Enter number of count: "); int n=scan.nextInt(); int[] nums=new int[n]; System.out.println("Enter the number one by one: "); for(int i=0;i<n;i++) { nums[i]=scan.nextInt(); } System.out.println("Enter target value: "); int target=scan.nextInt(); int[] result=twoSum(nums,target); System.out.println(result[0]+"st position "+nums[result[0]]+"+"+result[1]+"st postion "+nums[result[1]]+"="+target); } private static int[] twoSum(int[] nums, int target) { // TODO Auto-generated method stub HashMap<Integer,Integer> map=new HashMap<Integer,Integer>(); for(int i=0;i<nums.length;i++) { int complement=target-nums[i]; if(map.containsKey(complement)) { return new int[] {map.get(complement),i}; } else { map.put(nums[i], i); } } throw new IllegalArgumentException("No tow sum solution"); } }
OUTPUT