알고리즘 문제/프로그래머스

프로그래머스)최댓값과 최솟값

PJNull 2023. 4. 18.
728x90
반응형

문제 설명

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

제한 조건

 

s에는 둘 이상의 정수가 공백으로 구분되어 있습니다

 

입출력 예

 

s                    return
"1 2 3 4"          "1 4"
"-1 -2 -3 -4"    "-4 -1"
"-1 -1"             "-1 -1"

 

코드

 

#include <string>
#include <vector>
#include<bits/stdc++.h>
using namespace std;

string solution(string s) {
    string answer = "";
    vector<int> arr;
    int b=0;
    string total="";
    int cnt=0;
 
    for(int i=0;i<=s.size();i++)
    {
        
        if(s[i]==' '||i==s.size())
        {
            arr.push_back(stoi(total));
            total="";
            
        }
        else total+=s[i];
        
    }
   
    sort(arr.begin(),arr.end());
    
    total=total+to_string(arr.front())+" "+to_string(arr.back());
    
    answer+=total;
    
    
    return answer;
}
728x90
반응형

댓글