[프로그래머스/C++]Lv.0 - 2차원으로 만들기

YH J·2023년 4월 19일
0

프로그래머스

목록 보기
52/168

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/120842

내 풀이

int형 벡터 하나를 만들어서 num_list의 원소를 2개 넣고 answer에 push하고 초기화하고를 반복

내 코드

#include <string>
#include <vector>

using namespace std;

vector<vector<int>> solution(vector<int> num_list, int n) {
    vector<vector<int>> answer;
    vector<int> a;
    for(int i = 0; i < (num_list.size() / n); i++)
    {
        a.clear();
        for(int j = 0; j < n; j++)
        {
            a.push_back(num_list[i * n + j]);
        }
        answer.push_back(a);
    }
    
    return answer;
}

다른 사람의 풀이

#include <string>
#include <vector>

using namespace std;

vector<vector<int>> solution(vector<int> num_list, int n) {

    int r = num_list.size()/n;
    vector<vector<int>> answer(r,vector<int>(n));

    int ind = 0;
    for(int i =0; i < r; ++i)
    {
        for(int j = 0; j < n; ++j)
        {
            answer[i][j] = num_list[ind++];
        }
    }
    return answer;
}

다른 사람의 풀이 해석

아예 answer를 초기화시켜놓고 값을 넣어줌

profile
게임 개발자 지망생

0개의 댓글