-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path_1_TwoSum.java
More file actions
52 lines (41 loc) · 1.14 KB
/
Copy path_1_TwoSum.java
File metadata and controls
52 lines (41 loc) · 1.14 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
package io.github.tahanima.leetcode;
import java.util.Arrays;
/**
* @author tahanima
*/
public class _1_TwoSum {
public class Pair implements Comparable<Pair> {
public int first;
public int second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair o) {
return first - o.first;
}
}
public int[] twoSum(int[] nums, int target) {
int size = nums.length;
Pair [] numsAndIndices = new Pair[size];
int i = 0;
for (int n: nums) {
numsAndIndices[i] = new Pair(n, i++);
}
Arrays.sort(numsAndIndices);
i = 0;
size--;
while (i < size) {
int received = numsAndIndices[i].first + numsAndIndices[size].first;
if (received > target) {
size--;
} else if (received < target) {
i++;
} else {
return new int[]{numsAndIndices[i].second, numsAndIndices[size].second};
}
}
return new int[0];
}
}