File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ runtime 23 ms, beats 50.28%
3
+ memory 45.12 MB, beats 20.14%
4
+
5
+ time complexity: O(nlogn)
6
+ - numsArray 정렬: O(nlogn)
7
+ - binary search: O(nlogn)
8
+ - i iteration: O(n)
9
+ - i번째 binary search: O(logn)
10
+
11
+ space complexity: O(n)
12
+ - numsArray: O(n)
13
+ */
14
+
15
+ class Solution {
16
+ public int [] twoSum (int [] nums , int target ) {
17
+ ArrayList <Tuple > numsArray = IntStream .range (0 , nums .length )
18
+ .mapToObj (i -> new Tuple (i , nums [i ]))
19
+ .collect (Collectors .toCollection (ArrayList ::new ));
20
+
21
+ numsArray .sort (Comparator .comparing (tuple -> tuple .val ));
22
+
23
+ int n = numsArray .size ();
24
+
25
+ for (int i = 0 ; i < n ; i ++) {
26
+ int x = target - numsArray .get (i ).val ;
27
+ int j = -1 ;
28
+ int l = i + 1 ;
29
+ int r = n - 1 ;
30
+ boolean found = false ;
31
+ while (l <= r ) {
32
+ int m = (r - l ) / 2 + l ;
33
+ if (numsArray .get (m ).val == x ) {
34
+ j = m ;
35
+ found = true ;
36
+ break ;
37
+ } else if (numsArray .get (m ).val < x ) {
38
+ l = m + 1 ;
39
+ } else {
40
+ r = m - 1 ;
41
+ }
42
+ }
43
+
44
+ if (found ) {
45
+ int [] ans = new int [2 ];
46
+ ans [0 ] = numsArray .get (i ).ref ;
47
+ ans [1 ] = numsArray .get (j ).ref ;
48
+ return ans ;
49
+ }
50
+ }
51
+
52
+ return null ;
53
+ }
54
+
55
+ public class Tuple {
56
+ public final Integer ref ;
57
+ public final Integer val ;
58
+
59
+ public Tuple (Integer ref , Integer val ) {
60
+ this .ref = ref ;
61
+ this .val = val ;
62
+ }
63
+ }
64
+ }
You can’t perform that action at this time.
0 commit comments