-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathTwoNumbersSumToK_1.java
48 lines (37 loc) · 984 Bytes
/
TwoNumbersSumToK_1.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
38
39
40
41
42
43
44
45
46
47
48
// Daily Coding Problem: Problem #1
// using 2 pointers - array needs to be sorted
// time complexity is O(nlgn) + O(n) = O(nlgn)
import java.util.*;
public class TwoNumbersSumToK_1 {
public static void main(String[] args)
{
int[] array = new int[]{3,7,11,15};
int k = 17;
boolean found = twoNumbersSumToK(array, k);
System.out.println(found);
}
public static boolean twoNumbersSumToK(int[] inputArray, int k)
{
boolean found = false;
Arrays.sort(inputArray); // O(nlgn)
int i = 0;
int j = inputArray.length-1;
int sum;
while (i < j && !found)
{
sum = inputArray[i] + inputArray[j];
if (sum == k) {
found = true;
}
else if (sum < k)
{
i++;
}
else if (sum > k)
{
j--;
}
}
return found;
}
}