Geisha 2024. 8. 8. 00:42

 

코드 흐름

  •  weight을 정렬하여 낮은것 부터 차례대로 확인한다.
  • foreach문을 통해 weights 에 담긴 무게들을 하나하나 낮은것부터 확인한다.
  • a, b, c, d 즉 100이 들어오면 시소 짝궁을 이룰 수 있는 숫자들을 모두 만들어 둔다.
  • 만약 a,b,c,d가 map에 존재한다면 그 갯수를 answer에 더한다.
  • 이후 i 를 확인했으므로 map에 getOrDefault 문을 사용하여 i무게의 갯수를 적어둔다.

 

import java.util.*;
class Solution {
    public long solution(int[] weights) {
        long answer = 0;
        Arrays.sort(weights);
        Map<Double,Integer> map = new HashMap<>();
        for(int i : weights){
            double a = i * 1.0;
            double b = (i * 2.0) / 3.0;
            double c = i / 2.0;
            double d = (i * 3.0) / 4.0;
            if(map.containsKey(a)) answer+= map.get(a);
            if(map.containsKey(b)) answer+= map.get(b);
            if(map.containsKey(c)) answer+= map.get(c);
            if(map.containsKey(d)) answer+= map.get(d);
            map.put((i*1.0),map.getOrDefault((i*1.0),0)+1);
        }
        return answer;
    }
}