-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoupleSum.java
More file actions
112 lines (88 loc) · 2.85 KB
/
Copy pathCoupleSum.java
File metadata and controls
112 lines (88 loc) · 2.85 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
100
101
102
103
104
105
106
107
108
109
110
111
112
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Scanner;
public class CoupleSum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Integer> arr = new ArrayList<Integer>();
arr = scanArray(in);
int sum = in.nextInt();
int[] res = new int[2];
res = coupleSum2(arr, sum);
String index_pair = "" + res[0] + " " + res[1];
System.out.println(index_pair);
}
public static int[] coupleSum1(ArrayList<Integer> arr, int sum) {
int[] res = new int[2];
for(int i=0; i<arr.size(); i++) {
for(int j=i+1; j<arr.size(); j++) {
if(arr.get(i) + arr.get(j) == sum) {
res[0] = i;
res[1] = j;
return res;
}
}
}
res[0] = -1;
res[1] = -1;
return res;
}
public static int[] coupleSum2(ArrayList<Integer> arr, int sum) {
int[] res = new int[2];
for(int i=0; i<arr.size(); i++) {
int j = binarySearch(arr, i+1, arr.size()-1, sum-arr.get(i));
if(j>=0) {
res[0] = i;
res[1] = j;
return res;
}
}
res[0] = -1;
res[1] = -1;
return res;
}
public static int[] coupleSum3(ArrayList<Integer> arr, int sum) {
int[] res = new int[2];
int head = 0, tail = arr.size()-1;
while(head<tail) {
if(arr.get(head) + arr.get(tail) == sum) {
res[0] = head;
res[1] = tail;
return res;
} else if(arr.get(head) + arr.get(tail) > sum) {
tail--;
} else {
head++;
}
}
res[0] = -1;
res[1] = -1;
return res;
}
public static ArrayList<Integer> scanArray(Scanner in) {
// scan line of text
String line = in.nextLine();
// convert line of text into array of strings (tokens)
String[] tokens = line.split(" ");
// convert array of strings into array of integers
ArrayList<Integer> arr = new ArrayList<Integer>();
for (String token : tokens) {
if (!token.isEmpty()) // some tokens may be empty (e.g. with trailing spaces)
arr.add(Integer.parseInt(token));
}
return arr;
}
public static int binarySearch(ArrayList<Integer> arr, int head, int tail, int key) {
if(head>tail) {
return -1;
}
int k = (head + tail) / 2;
if(arr.get(k) == key) {
return k;
} else if(key < arr.get(k)) {
return binarySearch(arr, head, k-1, key);
} else {
return binarySearch(arr, k+1, arr.size()-1, key);
}
}
}