File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed
minjeong/TwoPointer_SlidingWindow Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change 1+ import sys
2+ input = sys .stdin .readline
3+
4+ N = int (input ())
5+ coding = list (map (int , input ().split ()))
6+ coding .sort ()
7+ answer = 0
8+
9+ for i in range (N ):
10+ target = - coding [i ]
11+ left = i + 1
12+ right = N - 1
13+
14+ while left < right :
15+ two_sum = coding [left ] + coding [right ]
16+ if two_sum < target :
17+ left += 1
18+ elif two_sum > target :
19+ right -= 1
20+ else : # two_sum == target
21+ if coding [left ] != coding [right ]:
22+ left_value = coding [left ]
23+ right_value = coding [right ]
24+
25+ # 왼쪽에 같은 값(left_value)이 연속으로 몇 명 있는지 센다
26+ cnt_left = 1
27+ while left + cnt_left < right and coding [left + cnt_left ] == left_value :
28+ cnt_left += 1
29+
30+ # 오른쪽에 같은 값(right_value)이 연속으로 몇 명 있는지 센다
31+ cnt_right = 1
32+ while right - cnt_right > left and coding [right - cnt_right ] == right_value :
33+ cnt_right += 1
34+
35+ # 이 조합들 각각은 전부 서로 다른 학생 조합이므로
36+ # 경우의 수 = cnt_left * cnt_right
37+ answer += cnt_left * cnt_right
38+
39+ # 세야 할 학생을 처리했으므로, 포인터 한 번에 이동
40+ left += cnt_left
41+ right -= cnt_right
42+
43+ else : # coding[left] == coding[right]
44+ # 이 구간에 남은 학생 수
45+ m = right - left + 1
46+
47+ # m명 중 2명을 뽑는 조합 수 C(m, 2)
48+ answer += m * (m - 1 ) // 2
49+
50+ # i에 대해 셀 조합 종료
51+ break
52+
53+ print (answer )
You can’t perform that action at this time.
0 commit comments