Make Unreal REAL.
article thumbnail
Level 2. n^2 배열 자르기

 

 

n x n 크기의 배열을 직접 만들어 모든 값을 할당할 필요도 없고, 매번 사이클을 많이 잡아먹는 나누기, 나머지 연산으로 인덱스를 구할 필요도 없다.

 

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> solution(int n, long long left, long long right)
{
    vector<int> answer(right - left + 1);
    int r = left / n;
    int c = left % n;

    auto clamp = [](int val, int minVal, int maxVal) { return max(minVal, min(val, maxVal)); };

    do
    {
        answer[answer.size() - (right - left + 1)] = clamp(++c, r + 1, n);

        if (c == n)
            ++r, c = 0;
    }
    while (++left <= right);

    return answer;
}

 

다른 사람의 풀이는 행을 이용해 최솟값을 Clamp하지 않고, 이 2차원 배열이 대칭 행렬이라는 점을 이용해 행과 열 중 큰 값을 넣어주었다.

 

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> solution(int n, long long left, long long right)
{
    vector<int> answer(right - left + 1);
    int r = left / n;
    int c = left % n;

    do
    {
        answer[answer.size() - (right - left + 1)] = max(++c, r + 1);

        if (c == n)
            ++r, c = 0;
    }
    while (++left <= right);

    return answer;
}

'자료구조 & 알고리즘 > 프로그래머스' 카테고리의 다른 글

Level 0. 2의 영역  (0) 2023.04.26
Level 0. qr code  (0) 2023.04.25
Level 2. 무인도 여행  (0) 2023.04.23
Level 2. 피보나치 수  (0) 2023.04.22
Level 2. [1차] 캐시  (0) 2023.04.21
profile

Make Unreal REAL.

@diesuki4

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그