forked from destiny1020/algorithm_playground
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
99 lines (84 loc) · 1.61 KB
/
TwoSum.java
File metadata and controls
99 lines (84 loc) · 1.61 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package chap1;
import java.util.Arrays;
import gadget.ArrayGenerator;
import gadget.Sorts;
public class TwoSum
{
private int[] array;
private int size;
private int low;
private int high;
private int count;
public TwoSum(int size, int low, int high)
{
this.size = size;
this.low = low;
this.high = high;
this.array = ArrayGenerator.generateIntArray(size, low, high);
// this.array = new int[]{-10, -9, -8, -8, -7, 8, 8, 8, 8, 8};
this.init();
}
private void init()
{
Arrays.sort(array);
}
public void bruteProcess()
{
for(int i = 0; i < this.size; i++)
{
for(int j = i + 1; j < this.size; j++)
{
if(array[i] + array[j] == 0)
{
count++;
}
}
}
}
public void process()
{
for(int i = 0; i < this.size; i++)
{
// int index = Sorts.binarySearch(-array[i], array);
int[] results = Sorts.binarySearchExtend(-array[i], array);
if(results[0] > i)
{
this.count += results[1];
// System.out.println(i + " - " + array[i] + " && " + index + " - " + (-array[i]));
}
}
}
public void processFast()
{
for(int i = 0; i < this.size; i++)
{
if(array[i] > 0)
{
return;
}
// int index = Sorts.binarySearch(-array[i], array);
int[] results = Sorts.binarySearchExtend(-array[i], array);
if(results[0] > i)
{
this.count += results[1];
// System.out.println(i + " - " + array[i] + " && " + index + " - " + (-array[i]));
}
}
}
public int getCount()
{
return count;
}
public void setCount(int count)
{
this.count = count;
}
public int getLow()
{
return low;
}
public int getHigh()
{
return high;
}
}