[프로그래머스] 최댓값과 최솟값

dev-log·2021년 11월 30일
0

나의 풀이

#include <string>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

string solution(string s) {
    string answer = "";
    vector<int> arr;
    bool isminus=false;
    string temp="";
    for(int i=0;i<s.size();i++){
        while(true){
        if(s[i]==' ') break;
        if(s[i]=='-') isminus=true;
            temp+=s[i];
            i++;
        }
        arr.push_back(stoi(temp));
        temp="";
        isminus=false;
    }
    sort(arr.begin(),arr.end());
 
    answer=to_string(arr[0])+' '+to_string(arr[arr.size()-1]);
    
    return answer;
}

다른 사람 풀이

#include <string>
#include <vector>
#include <algorithm>
using namespace std;

string solution(string s) {
    string answer = "";
    string sTemp = "";
    vector<int> vecInteger;

    for (int i = 0; i < s.size(); i++)
    {
        if (s[i] == ' ')
        {
            vecInteger.push_back(stoi(sTemp));
            sTemp.clear();
            continue;
        }

        sTemp += s[i];
    }

    vecInteger.push_back(stoi(sTemp));

    sort(vecInteger.begin(), vecInteger.end());

    answer += to_string(vecInteger.front());
    answer += ' ';
    answer += to_string(vecInteger.back());

    return answer;
}

대략적인 풀이 방법은 비슷한데 훨씬 깔끔한 것 같다.

profile
배운 걸 기록하는 곳입니다.

0개의 댓글