Two sum problem | Java program

Two sum problem | Java program
Advertisement
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:

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:

Example 2

Input: nums = [3,2,4], target = 6
Output: [1,2]


Example 3:

Example 3

Input: nums = [3,3], target = 6
Output: [0,1]


Method 1 : Brute force(Loop)

" style="position:absolute;top:0;left:0;width:100%;height:100%;border:0;" allowfullscreen>
JAVApackage 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

OUTPUT

Image description

Method 2 : Hashmap

" style="position:absolute;top:0;left:0;width:100%;height:100%;border:0;" allowfullscreen>
JAVA
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

OUTPUT

Image description
Share this article:
Advertisement

Comments (0)

No comments yet. Be the first to share your thoughts!