728x90
투 포인터 & 정렬 문제
// 투 포인터 & 정렬
import Foundation
var n = Int(readLine()!)!
var input : [Int] = readLine()!.split(separator: " ").map{Int(String($0))!}
input.sort()
var count : Int = 0
func solve(_ s: inout Int, _ e: inout Int, _ g: Int) {
var maxIdx = n
while s < e {
let tmp = input[s] + input[e]
if tmp < g {
s += 1
} else if tmp == g {
if input[s] == input[e] {
count += e - s
} else {
if maxIdx > e {
maxIdx = e
while maxIdx > 0 && input[maxIdx - 1] == input[e] {
maxIdx -= 1
}
}
count += e - maxIdx + 1
}
s += 1
} else {
e -= 1
}
}
}
for i in 0..<n-1 {
var start = i + 1
var end = n - 1
let goal = -input[i]
solve(&start, &end, goal)
}
print(count)
'Computer Science > Algorithm' 카테고리의 다른 글
[프로그래머스] 미로 탈출 (Swift) (2) | 2024.03.17 |
---|---|
[백준] 7576, 토마토 (Swift) (0) | 2024.02.13 |
[백준] 2644, 촌수계산(C++, BFS) (0) | 2023.09.02 |
[백준] 13414, 수강신청 (C++, 해시맵) (0) | 2023.08.10 |
[C언어] 표준 입력 함수, scanf() 함수의 오류 찾기 (0) | 2023.05.31 |