프로그래머스 - n^2 배열 자르기

well-life-gm·2021년 11월 3일
0

프로그래머스

목록 보기
22/125
post-thumbnail

프로그래머스 - n^2 배열 자르기

n의 값이 10의 7승까지이기 때문에 map을 만들고, index로 풀면 시간초과가 발생한다.
따라서 주어진 left와 right를 for-loop으로 돌면서 바로 수식으로 풀어야 한다.

row, col는 몫과 나머지를 통해서 구할 수 있고, answer에 들어갈 값은 구해진 row, col 중 큰 값으로 하면 된다.

코드를 보는게 이해가 쉬울 듯 하다.

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

using namespace std;

vector<int> solution(int n, long long left, long long right) {
    vector<int> answer;
    
    for(long long i=left; i<=right; i++) {
        int row = (int)(i / n);
        int col = (int)(i % n);
        int val = max(row, col) + 1;
        answer.push_back(val);
    }
    
    return answer;
}

결과

profile
내가 보려고 만든 블로그

0개의 댓글