[프로그래머스] lv2 N으로 표현
[출처 - 프로그래머스 lv2 시소 짝꿍]
https://school.programmers.co.kr/learn/courses/30/lessons/152996
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 설명
제한 사항
입출력 예
풀이
2 | 3 | 4 | |
2 | 자기 자신 | 2/3 * x | 2/4 * x |
3 | 3/2 * x | 자기 자신 | 3/4 *x |
4 | 4/2 * x | 4/3 * x | 자기 자신 |
위 표에서 행은 x, 열은 y라고 하자.
문제에서 시소로부터 떨어진 거리가 2, 3, 4m라고 했으니 (2,3), (2,4), (3,4)의 비율이 존재함을 알 수 있다. 내항의 곱 = 외항의 곱 에 따라서 위 표처럼 그려 볼 수 있다. 마지막으로 몸무게가 같을 때, 즉 (1,1) 일 때도 계산해주면 된다. 즉, 표에 6가지 경우의 수와 자기 자신과 몸무게가 같을 때 1가지, 총 7가지의 경우의 수를 따져서 구현해주면 된다.
전체 코드
import java.util.*;
class Solution {
public long solution(int[] weights) {
long answer = 0;
HashMap<Integer, Integer> hm = new HashMap<>();
Set<Integer> set = new HashSet<>();
for(int i = 0; i < weights.length; i++) {
hm.put(weights[i], hm.getOrDefault(weights[i], 0) + 1);
set.add(weights[i]);
}
for(int weight: set) {
long people = hm.get(weight);
// Y = 2y
int tmp = weight*2;
if(tmp%3 == 0 && hm.containsKey(tmp/3)) {
answer += hm.get(tmp/3)*people;
}
if(tmp%4 == 0 && hm.containsKey(tmp/4)) {
answer += hm.get(tmp/4)*people;
}
// Y = 3y
tmp = weight*3;
if(tmp%2 == 0 && hm.containsKey(tmp/2)) {
answer += hm.get(tmp/2)*people;
}
if(tmp%4 == 0 && hm.containsKey(tmp/4)) {
answer += hm.get(tmp/4)*people;
}
// Y = 4y
tmp = weight*4;
if(tmp%3 == 0 && hm.containsKey(tmp/3)) {
answer += hm.get(tmp/3)*people;
}
if(tmp%2 == 0 && hm.containsKey(tmp/2)) {
answer += hm.get(tmp/2)*people;
}
// 1:1
if(people > 1) {
// 자기 자신과 짝이 될 수 없음
// ex) answer = 5만x49,999일 경우
// long = int x int 이므로 long poeple로 바꿔줘야함
answer += people*(people-1)/2;
}
hm.remove(weight);
}
return answer;
}
}