문제 시소 짝꿍
처음에는 모든 사람들의 무게들을 일일히 비교해가면서 결과를 찾았다. 당연스럽게(?) 시간초과가 났다.
시소에 탔을때 무게를 비교하기 위해서는 먼저 오름차순으로 정렬을 했다.
무게가 덜나가는 사람과 무게가 더나가는 사람이 시소를 탔을 때 시소 짝꿍이 될 수 있는 경우는 (1,1) (2,3) (2,4) (3,4) 인 경우만 있기 때문이다.
같은 무게인 사람들은 다시 짝꿍을 찾는 시도를 하지 않기 위해 HashMap을 이용했다.
import java.util.*;
class Solution {
public long solution(int[] weights) {
long answer = 0;
Arrays.sort(weights);
//중복된 값은 사용하지 않기 위해 hashmap사용
Map<Double,Integer> maps = new HashMap<>();
for(int w : weights)
{
double a = w * 1.0;
double b = a / 2.0;
double c = (w * 2.0) / 3.0;
double d = (w * 3.0) /4.0;
if(maps.containsKey(a)) answer += maps.get(a);
if(maps.containsKey(b)) answer += maps.get(b);
if(maps.containsKey(c)) answer += maps.get(c);
if(maps.containsKey(d)) answer += maps.get(d);
maps.put(a , maps.getOrDefault(a,0)+1);
}
return answer;
}
}