-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathTwoSumGreater.java
34 lines (31 loc) · 974 Bytes
/
TwoSumGreater.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
package algorithm.pointers.twosum;
import java.util.Arrays;
/**
* Given an array of integers, find how many pairs in the array such that their sum is bigger than a specific target number.
* Please return the number of pairs.
*/
public class TwoSumGreater {
// Sort + TwoPointers
// Time O(nlogn + n) = O(n), Space O(n)
public int twoSumGreater(int[] array, int target) {
if (array == null || array.length == 0) {
return 0;
}
Arrays.sort(array);
int left = 0;
int right = array.length - 1;
int count = 0;
while (left < right) {
int sum = array[left] + array[right];
if (sum > target) {
// all the pair that left in the range [left, right)
// will be greater than target
count += right - left;
right--;
} else {
left++;
}
}
return count;
}
}