-
Notifications
You must be signed in to change notification settings - Fork 288
/
Copy pathAC_two_points_nlogn.java
71 lines (62 loc) · 1.86 KB
/
AC_two_points_nlogn.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
/*
* Author: illuz <iilluzen[at]gmail.com>
* File: AC_two_ponits_nlogn.java
* Create Date: 2015-02-01 22:46:09
* Descripton: Two_points
*/
import java.util.Arrays;
import java.util.Scanner;
public class Solution {
static class Pair implements Comparable<Pair> {
int value, index;
public Pair(int v, int id) {
value = v;
index = id;
}
@Override
public int compareTo(Pair b) {
return this.value - b.value;
}
}
public static int[] twoSum(int[] numbers, int target) {
int[] res = new int[2];
Pair[] pairs = new Pair[numbers.length];
// get pairs and sort
for (int i = 0; i < numbers.length; ++i) {
pairs[i] = new Pair(numbers[i], i + 1);
}
Arrays.sort(pairs);
// two points
int left = 0, right = numbers.length - 1, sum = 0;
while (left < right) {
sum = pairs[left].value + pairs[right].value;
if (sum == target) {
res[0] = pairs[left].index;
res[1] = pairs[right].index;
if (res[0] > res[1]) {
// swap them
res[0] ^= res[1];
res[1] ^= res[0];
res[0] ^= res[1];
}
break;
} else if (sum > target) {
--right;
} else {
++left;
}
}
return res;
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int[] numbers = new int[n];
for (int i = 0; i < numbers.length; ++i) {
numbers[i] = cin.nextInt();
}
int target = cin.nextInt();
int[] res = twoSum(numbers, target);
System.out.println(res[0] + " " + res[1]);
}
}