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.
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)
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
Method 2 : Hashmap
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 map=new HashMap();
for(int i=0;i
OUTPUT
Frequently asked questions
What is the time complexity of each Two Sum method?
The brute-force method checks every pair with two nested loops, so it is O(n²) time and O(1) extra space. The HashMap method makes one pass over the array, so it is O(n) time and uses O(n) extra space for the map.
Why does the HashMap method store the index as the value?
For each number, the program looks up
target - number in the map. If it is there, the stored index is the other half of the answer, so both indices are known in a single pass without searching the array again.Can the same element be used twice?
No. The problem says you may not use the same element twice, which is why the brute-force inner loop starts at
i + 1. With nums = [3,3] and target = 6, the answer is [0,1] because they are two different elements.What if no two numbers add up to the target?
The problem guarantees exactly one solution. In your own code, return an empty array or throw an exception when the loop ends without finding a pair.
Comments
0Please sign in to leave a comment.
No comments yet
Be the first to share your thoughts!