본문 바로가기

Algorithm/프로그래머스

프로그래머스 최댓값과 최솟값 C++

반응형

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 


- 문제

  주어진 문자열에서 최댓값과 최솟값을 반환하는 문제이다.

 


- 풀이

#include <string>
#include <vector>
#include <sstream>
#include <algorithm>

using namespace std;

string solution(string s) {
    string answer = "";
    vector<int> nums;
    string temp;
    int size;
    stringstream ss(s);
    while(ss >> temp){
        nums.push_back(stoi(temp));
    }
    size = nums.size() - 1;
    sort(nums.begin(),nums.end());
    answer += to_string(nums[0]) + " " + to_string(nums[size]);
    return answer;
}

 

vector에 모든 값을 저장한 후 sort해서 최솟값과 최댓값을 구했다.

 

 

 

  


- 기억할 것!

 nums[0]이랑 nums[nums.size() - 1]은

 

nums.front()이랑 nums.back()으로 대체가 가능하다.

반응형