-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSample.java
More file actions
38 lines (31 loc) · 1016 Bytes
/
Sample.java
File metadata and controls
38 lines (31 loc) · 1016 Bytes
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
import java.util.*;
public class Sample
{
// Function to find a pair in an array with a given sum using hashing
public static void findDuplicates(int[] nums)
{
// create an empty HashMap
List<Integer> map = new ArrayList<>();
// do for each element
for (int i = 0; i < nums.length; i++)
{
// check if pair (nums[i], target-nums[i]) exists
// if the difference is seen before, print the pair
if (map.remove(nums[i]))
{
System.out.printf("Duplicate element (%d)%n",
nums[map.get(i)]);
//return;
}
// store index of the current element in the map
map.put(nums[i], i);
}
// we reach here if the pair is not found
//System.out.println("Pair not found");
}
public static void main (String[] args)
{
int[] nums = {11,1,10,7,3,9,7,4,8,11 };
findDuplicates(nums);
}
}