출처: https://school.programmers.co.kr/learn/courses/30/lessons/152996
문제 설명
어느 공원 놀이터에는 시소가 하나 설치되어 있습니다. 이 시소는 중심으로부터 2(m), 3(m), 4(m) 거리의 지점에 좌석이 하나씩 있습니다.
이 시소를 두 명이 마주 보고 탄다고 할 때, 시소가 평형인 상태에서 각각에 의해 시소에 걸리는 토크의 크기가 서로 상쇄되어 완전한 균형을 이룰 수 있다면 그 두 사람을 시소 짝꿍이라고 합니다. 즉, 탑승한 사람의 무게와 시소 축과 좌석 간의 거리의 곱이 양쪽 다 같다면 시소 짝꿍이라고 할 수 있습니다.
사람들의 몸무게 목록 weights이 주어질 때, 시소 짝꿍이 몇 쌍 존재하는지 구하여 return 하도록 solution 함수를 완성해주세요.
제한 사항
2 ≤ weights의 길이 ≤ 100,000
100 ≤ weights[i] ≤ 1,000
몸무게 단위는 N(뉴턴)으로 주어집니다.
몸무게는 모두 정수입니다.
입출력 예
weights result
[100,180,360,100,270] 4
입출력 예 설명
{100, 100} 은 서로 같은 거리에 마주보고 앉으면 균형을 이룹니다.
{180, 360} 은 각각 4(m), 2(m) 거리에 마주보고 앉으면 균형을 이룹니다.
{180, 270} 은 각각 3(m), 2(m) 거리에 마주보고 앉으면 균형을 이룹니다.
{270, 360} 은 각각 4(m), 3(m) 거리에 마주보고 앉으면 균형을 이룹니다.
우선, 문제 풀이 자체는 이해가 가는 내용이지만, 너무 생소했다.
import java.util.HashMap;
import java.util.Map;
public class Solution {
public long solution(int[] weights) {
long answer = 0;
Map<Double, Integer> weightCount = new HashMap<>();
for (int weight : weights) {
weightCount.put((double) weight, weightCount.getOrDefault((double) weight, 0) + 1);
}
for (double key : weightCount.keySet()) {
if (weightCount.get(key) > 1) {
int a = weightCount.get(key);
answer += (long) a * (a - 1) / 2;
}
if (weightCount.containsKey(key * 2 / 3)) {
answer += (long) weightCount.get(key) * weightCount.get(key * 2 / 3);
}
if (weightCount.containsKey(key / 2)) {
answer += (long) weightCount.get(key) * weightCount.get(key / 2);
}
if (weightCount.containsKey(key * 3 / 4)) {
answer += (long) weightCount.get(key) * weightCount.get(key * 3 / 4);
}
}
return answer;
}
}
각 몸무게(double) 가 몇 번 나왔는지 카운트하는 해시맵
Map<Double, Integer> weightCount = new HashMap<>();
weights 배열을 돌면서 몸무게마다 등장 횟수 누적
주의: double로 변환했기 때문에 부동소수점 오차 위험 존재
for (int weight : weights) {
weightCount.put((double) weight, weightCount.getOrDefault((double) weight, 0) + 1);
}
저장된 모든 몸무게에 대해 하나씩 처리 시작
for (double key : weightCount.keySet()) {
같은 무게끼리 1:1 비율로 시소 탈 수 있음
등장 횟수가 2개 이상인 경우, 조합 공식 nC2 = n(n-1)/2 로 쌍 수 계산
if (weightCount.get(key) > 1) {
int a = weightCount.get(key);
answer += (long) a * (a - 1) / 2;
}
현재 몸무게 * 2 / 3 = 상대방 몸무게일 때 → 2:3 시소 가능
if (weightCount.containsKey(key 2 / 3)) {
answer += (long) weightCount.get(key) weightCount.get(key * 2 / 3);
}
현재 몸무게 / 2 = 상대방 몸무게 → 2:1
if (weightCount.containsKey(key / 2)) {
answer += (long) weightCount.get(key) * weightCount.get(key / 2);
}
3:4 시소를 체크 (올바른 조건)
if (weightCount.containsKey(key 3 / 4)) {
answer += (long) weightCount.get(key) weightCount.get(key * 3 / 4);
}
그외에 풀이
import java.util.*;
class Solution {
public long solution(int[] weights) {
long answer = 0;
// 무게 등장 횟수 저장
Map<Integer, Long> map = new HashMap<>();
// 가능한 비율 목록
int[][] ratios = {
{1, 1},
{2, 3},
{3, 2},
{3, 4},
{4, 3}
};
for (int weight : weights) {
for (int[] r : ratios) {
int num = r[0], den = r[1];
// 비율 곱해서 짝이 될 수 있는 weight 계산
int target = weight * num;
// 나누어떨어지는 경우만
if (target % den == 0) {
int pair = target / den;
if (map.containsKey(pair)) {
answer += map.get(pair);
}
}
}
// 현재 weight 기록
map.put(weight, map.getOrDefault(weight, 0L) + 1);
}
return answer;
}
}