최댓값과 최솟값

유태형·2022년 2월 9일
0

문제

문제 분석

문자열의 값들을 구분해야 하고 최댓값과 최솟값을 구해야 한다!


풀이

처음엔 Arrays클래스를 이용하여 정렬후 최솟값(0번 index)최댓값(마지막 index)을 문자열에 더해 반환하는 코드를 작성 하였으나 다른사람의 풀이 중 정렬할 필요 없이 최댓값과 최솟값을 바로 구하는 예제를 보고 바꿔 보았다.

for(int i=0;i<temp.length;i++){ 
       n = Integer.parseInt(temp[i]); //각 요소마다 확인
       
       if(min > n) min = n; //최소면 최소
       if(max < n) max = n; //최대면 최대
   }

코드

class Solution {
    public String solution(String s) {
        String[] temp = s.split(" ");
        int min, max, n;
        min = max = Integer.parseInt(temp[0]); //0번 인덱스로 초기화
        for(int i=0;i<temp.length;i++){ //1번 인덱스부터 순차적으로 최대와 최소 비교
            n = Integer.parseInt(temp[i]); //각 요소마다 확인
            
            if(min > n) min = n; //최소면 최소
            if(max < n) max = n; //최대면 최대
        }
        
        return min + " " + max;
    }
}

GitHub

https://github.com/ds02168/Study_Algorithm/blob/master/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4/%EC%9E%90%EB%B0%94/Level2/%EC%B5%9C%EB%8C%93%EA%B0%92%EA%B3%BC%20%EC%B5%9C%EC%86%9F%EA%B0%92.txt

profile
오늘도 내일도 화이팅!

0개의 댓글

관련 채용 정보