forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforest000014.java
More file actions
64 lines (54 loc) · 1.61 KB
/
forest000014.java
File metadata and controls
64 lines (54 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
/*
runtime 23 ms, beats 50.28%
memory 45.12 MB, beats 20.14%
time complexity: O(nlogn)
- numsArray 정렬: O(nlogn)
- binary search: O(nlogn)
- i iteration: O(n)
- i번째 binary search: O(logn)
space complexity: O(n)
- numsArray: O(n)
*/
class Solution {
public int[] twoSum(int[] nums, int target) {
ArrayList<Tuple> numsArray = IntStream.range(0, nums.length)
.mapToObj(i -> new Tuple(i, nums[i]))
.collect(Collectors.toCollection(ArrayList::new));
numsArray.sort(Comparator.comparing(tuple -> tuple.val));
int n = numsArray.size();
for (int i = 0; i < n; i++) {
int x = target - numsArray.get(i).val;
int j = -1;
int l = i + 1;
int r = n - 1;
boolean found = false;
while (l <= r) {
int m = (r - l) / 2 + l;
if (numsArray.get(m).val == x) {
j = m;
found = true;
break;
} else if (numsArray.get(m).val < x) {
l = m + 1;
} else {
r = m - 1;
}
}
if (found) {
int[] ans = new int[2];
ans[0] = numsArray.get(i).ref;
ans[1] = numsArray.get(j).ref;
return ans;
}
}
return null;
}
public class Tuple {
public final Integer ref;
public final Integer val;
public Tuple(Integer ref, Integer val) {
this.ref = ref;
this.val = val;
}
}
}