Algorithm/PS

[C++, python] 프로그래머스, 최댓값과 최솟값

chanwoong1 2023. 2. 24. 13:43
728x90

문제 링크

 

프로그래머스

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

programmers.co.kr

문제 풀이

이 문제는 숫자와 공백으로 이루어진 문자열에서 숫자를 뽑고, 최댓값과 최솟값을 찾는 문제이다.

C++에서는 파이썬처럼 split 함수를 사용할 수 없기 때문에, split함수를 직접 구현하거나, 문자열에서 특정 문자를 구분자로 활용해 부분적인 문자열을 추출하는 방법으로 <sstream> 라이브러리와 getline을 활용해 공백을 분리해줄 수 있다.

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int main(){
    // 공백 분리할 문자열 선언
    string input = "123 456 -789";

    // 문자열을 스트림화
    stringstream ss(input);

    // 분리된 문자열을 담아줄 문자열
    string number;

    // 공백 분리 결과를 저장할 배열
    vector<int> numbers;

    // 스트림을 한 줄씩 읽어, 공백 단위로 분리한 뒤, stoi함수로 int형으로 변환 후 결과 배열에 저장
    while (getline(ss, number, ' ')){
        numbers.push_back(stoi(number));
    }
}

위의 방법으로 수를 제대로 벡터에 저장했다면, sort함수를 이용해 정렬 후, 벡터의 첫 번째 요소와 마지막 요소를 뽑아 요구에 맞게 반환시키면 된다.

정답 코드

C++

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

using namespace std;

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

python

def solution(s):
    s_lst = list(map(int, s.split()))
    answer = str(min(s_lst)) + " " + str(max(s_lst))
    return answer

 

728x90