알고리즘

최댓값과 최솟값

LeeDiculous 2022. 12. 29. 15:33

문자열 s 에는 공백으로 구분된 숫자들이 저장되어 있습니다. str 에 나타나는 숫자 중 최소값과 최대값을 찾아 이를 "(최소값) (최대값)"형태의 문자열을 반환하는 함수, solution 을 완성하세요.

예를들어 s가 "1 2 3 4"라면 "1 4"를 리턴하고, "-1 -2 -3 -4"라면 "-4 -1"을 리턴하면 됩니다.

    public String solution(String s) {
        String answer = "";
        int count = 0;
        int size = 0;
        int max = 0;
        int min = 0;

        //숫자를 비교할 배열의 길이를 먼저 구하자.
        while (count < s.length()) {
            if (s.charAt(count) == '-' || s.charAt(count) == ' ') {
                count++;
            } else {
                size++;
                count++;
            }
        }

        count = 0;

        int[] arr = new int[size];
        int arrcount = 0;

        // 비교하기 위해 배열안에 숫자 담기
        while (count < s.length()){
            if (s.charAt(count) == '-') {
                arr[arrcount] = (s.charAt(count + 1) - '0') * -1;
                count += 3;
            } else {
                arr[arrcount] = (s.charAt(count) - '0');
                count += 2;
            }
            arrcount++;
        }

        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length - 1; j++) {
                int z = arr[j];
                if (arr[j] > arr[j + 1]) {
                    arr[j] = arr[j + 1];
                    arr[j + 1] = z;
                }
            }
        }

        min = arr[0];
        max = arr[arr.length - 1];
        answer = (min + " " + max);
        System.out.println(answer);
        return answer;
    }

위 코드는 실행에는 성공하지만 테스트 케이스에서 전부 실패하는 코드였습니다. 이유가 무엇인지 찾아보니 두 자릿수 이상을 인식 못하는,,,😥 문제를 찾았으니 수정을 해보겠습니다.

    public String solution1(String s) {
        String answer = "";

        int count = 0;
        int size = 0;
        int arrCount = 0;
        String str = "";
        int max = 0;
        int min = 0;

        // <--- 1. String[] arr의 크기를 구하자. --->
        while (count < s.length()) {
            if (s.charAt(count) == ' ') {
                size++;
            }
            count++;
        }size += 1; // 배열의 크기는 공백 갯수 +1 이다.

        count = 0; // count 재사용을 위해 초기화.


        // <--- 2. String 배열에 각 숫자를 저장 --->
        String[] arr = new String[size];

        while (count < s.length()) {
            if (s.charAt(count) != ' ') {
                str = str +  String.valueOf(s.charAt(count));
                arr[arrCount] = str;
            } else {
                str = "";
                arrCount++;
            }
            count++;
        }

        //<--- 3. String을 int로 타입 변환 --->
        int[] arrInt = new int[arr.length];

        for (int i = 0; i < arrInt.length; i++) {
            arrInt[i] = Integer.parseInt(arr[i]);
        }

        //<--- 4. 오름차순 정렬 --->
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length - 1; j++) {
                int z = arrInt[j];
                if (arrInt[j] > arrInt[j + 1]) {
                    arrInt[j] = arrInt[j + 1];
                    arrInt[j + 1] = z;
                }
            }
        }

        //<--- 5. 최솟값 최댓값 반환하기 --->
        min = arrInt[0];
        max = arrInt[arrInt.length - 1];
        answer = (min + " " + max);
        return answer;
    }

다른 풀이도 한번 보겠습니다.

public class GetMinMaxString {
    public String getMinMaxString(String str) {
        String[] tmp = str.split(" ");
        int min, max, n;
        min = max = Integer.parseInt(tmp[0]);
        for (int i = 1; i < tmp.length; i++) {
                n = Integer.parseInt(tmp[i]);
            if(min > n) min = n;
            if(max < n) max = n;
        }

        return min + " " + max;

    }