-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTargetSumBy2.java
More file actions
76 lines (58 loc) · 1.85 KB
/
TargetSumBy2.java
File metadata and controls
76 lines (58 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
program to display 2 numbers whose sum is equal to the given number .
input
an array of size 6 , a number n
output
2 numbers in the form of array whose sum is equal to that number
example
input
4 5 12 -2 8 4
10
output
[12,-2]
*/
/*
@ author : saurabh vaish
*/
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class TargetSumBy2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s[] = sc.nextLine().split(" "); // a space seprated string then stored in string array
int ar[] = new int[6];
for(int i=0;i<s.length;i++)
{
ar[i] = Integer.parseInt(s[i]); // store string elements in array
}
int n = sc.nextInt();
int c=0;
Map<Integer,Integer> map = new HashMap<Integer, Integer>(); // hashmap to remove duplicate intries
for (int i=0;i<ar.length;i++)
{
// if a number is taken then n-thatnumber should be in the array
int num = n-ar[i];
for (int j=0;j<ar.length;j++)
{
if(j==i) // if same index number comes it should be coounted
continue;
if(num==ar[j])
{ c++;
if(!(map.containsKey(num))) // check if the other number is present in the hashmap or not if not then store in it
map.put(ar[i],num);
}
}
}
if(c==0)
{
System.out.println("no numbers found");
}
else
{
for(Map.Entry entry : map.entrySet()) { // for retriving hashmap entries
System.out.println("["+entry.getKey()+","+entry.getValue()+"]");
}
}
}
}