forked from anitaa1990/Android-Cheat-sheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SumOfTwoValues.java
37 lines (30 loc) · 1.11 KB
/
SumOfTwoValues.java
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
package arrays;
import java.util.HashSet;
import java.util.Set;
public class SumOfTwoValues {
/*
* Given an array of integers and a value, determine if there are any two integers in the array which sum
* equal to the given value.
*
* Runtime Complexity - Linear, O(n).
* Memory Complexity - Linear, O(n).
*
* Step 1: Iterate through the array
* Step 2: At each element, check if the set contains the difference between the value and the current element.
* eg: if value = 10 & current element arr[0] = 5, check if 10-5 is present in the set.
* Step 3: If not, add the current element to the set
* */
public static void findSumOfTwoValues(int []arr, int value) {
Set<Integer> map = new HashSet<>();
for(int i=0; i<arr.length; i++) {
if(map.contains(value-arr[i])) {
System.out.println(value-arr[i]+ " "+ arr[i]);
break;
} else map.add(arr[i]);
}
}
public static void main(String[] args) {
int[] arr = {12, 5, 9, 19};
findSumOfTwoValues(arr, 14);
}
}