23년 7월 14일 [알고리즘 - 이분탐색]

sua·2023년 7월 14일
0

알고리즘 가보자고

목록 보기
55/101

백준 2022번 사다리

문제


나의 풀이

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double x = sc.nextDouble();
        double y = sc.nextDouble();
        double c = sc.nextDouble();
        double left = 0;
        double right = Math.min(x, y);
        while(Math.abs(right - left) > 1e-6) {
            double mid = (left + right) / 2.0;
            double d = mid;
            double h1 = Math.sqrt(x * x - d * d);
            double h2 = Math.sqrt(y * y - d * d);
            double h = (h1 * h2) / (h1 + h2);
            if(h > c) {
                left = mid;
            } else {
                right = mid;
            }
        }
        System.out.printf("%.3f\n", left);
    }
}

삼각형의 닮음을 이용하여 c = h1 x h2 / (h1 + h2)라는 식을 얻게 되고 이를 이용하여 이분 탐색을 한다.

결과


인프런 같은 빈도수 만들기

문제

나의 풀이

import java.util.Arrays;
import java.util.HashMap;

public class TheSameFrequency {
    public static int[] solution(String s) {
        int answer[] = new int[5];
        HashMap<Character, Integer> sh = new HashMap<>();
        for(char x : s.toCharArray()) {
            sh.put(x, sh.getOrDefault(x, 0) + 1); // 문자열의 빈도수 구하기
        }

        int max = Integer.MIN_VALUE;
        String tmp = "abcde";
        for(char key : tmp.toCharArray()) {
            if(sh.getOrDefault(key, 0) > max) {
                max = sh.getOrDefault(key, 0); // 빈도수 최대값 구하기
            }
        }
        for(int i = 0; i < tmp.length(); i++) {
            answer[i] = max - sh.getOrDefault(tmp.charAt(i), 0); // 각 문자의 필요 추가 개수 구하기
        }
        return answer;
    }
    public static void main(String[] args) {
        System.out.println(Arrays.toString(TheSameFrequency.solution("aaabc")));
        System.out.println(Arrays.toString(TheSameFrequency.solution("aabb")));
    }
}

빈도수 중에 최댓값을 구하고, 각 문자에 대해서 최댓값에서 자신의 빈도수를 뺀 값들을 정답 배열에 저장하여 리턴하면 된다.

결과

profile
가보자고

0개의 댓글