File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ // 배열을 정렬하여 투포인터로 접근하여 풀었습니다.
2+ // 정렬된 배열의 인덱스를 찾기 위해 indexOf 메소드를 만들어서 사용했습니다.
3+
4+ // 시간복잡도 : O(NlogN) -> 정렬을 위해 O(NlogN) + 투포인터로 O(N)이므로 O(NlogN)
5+ // 공간복잡도 : O(N) -> 정렬을 위해 복사한 배열이 필요하므로 O(N)
6+ class SolutionGotprgmer {
7+ public int [] twoSum (int [] nums , int target ) {
8+ int [] original = new int [nums .length ];
9+
10+ for (int i =0 ;i <nums .length ;i ++){
11+ original [i ] = nums [i ];
12+ }
13+ Arrays .sort (nums );
14+
15+ int l = 0 ;
16+ int r = nums .length -1 ;
17+ while (l <r ){
18+ int lV = nums [l ];
19+ int rV = nums [r ];
20+ int total = lV + rV ;
21+ if (total > target ){
22+ r -= 1 ;
23+ }
24+ else if (total < target ){
25+ l += 1 ;
26+ }
27+ else {
28+ int [] ans = indexOf (lV ,rV ,original );
29+ l = ans [0 ];
30+ r = ans [1 ];
31+ break ;
32+ }
33+ }
34+ return new int [] {l ,r };
35+ }
36+
37+ public int [] indexOf (int l ,int r , int [] nums ){
38+ int lIdx = -1 ;
39+ int rIdx = -1 ;
40+ for (int i = 0 ;i <nums .length ;i ++){
41+ if (nums [i ] == l ){
42+ lIdx = i ;
43+ break ;
44+ }
45+ }
46+ for (int i = nums .length -1 ;i >-1 ;i --){
47+ if (nums [i ] == r ){
48+ rIdx = i ;
49+ break ;
50+ }
51+ }
52+ return new int [] {lIdx ,rIdx };
53+ }
54+ }
You can’t perform that action at this time.
0 commit comments