forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPairDiff.java
72 lines (64 loc) · 1.78 KB
/
PairDiff.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.rampatra.arrays;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 5/18/15
* @time: 10:24 PM
*/
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Given an array ar[] of n numbers and another number x, determine whether
* or not there exists two elements in ar[] whose difference is exactly x.
* This problem is similar to {@link PairSum}.
*/
public class PairDiff {
/**
* Using sorting. If we use Merge Sort or Heap Sort
* then (-)(nlogn) in worst case. If we use Quick Sort
* then O(n^2) in worst case.
*
* @param ar
* @param x
* @return
*/
static boolean pairDiff(int ar[], int x) {
Arrays.sort(ar);
int len = ar.length;
for (int i = 0, j = 1; i < len && j < len; ) {
if (i != j && ar[j] - ar[i] == x) {
return true;
} else if (ar[j] - ar[i] < x) {
j++;
} else {
i++;
}
}
return false;
}
/**
* Using HashMap in O(n) time.
*
* @param ar
* @param x
* @param map
* @return
*/
static boolean pairDiff(int ar[], int x, Map<Integer, Integer> map) {
for (int i = 0; i < ar.length; i++) {
if (map.containsKey(x + ar[i])) {
return true;
}
map.put(ar[i], 1);
}
return false;
}
public static void main(String[] args) {
System.out.println(pairDiff(new int[]{-3, 4, -6, 1, 1}, -4));
System.out.println(pairDiff(new int[]{3, 1}, 2));
System.out.println(pairDiff(new int[]{-3, 4, -6, 1, 1}, -4, new HashMap<Integer, Integer>()));
System.out.println(pairDiff(new int[]{3, 1}, 2, new HashMap<Integer, Integer>()));
}
}