프로그래머스

[코딩테스트 연습] n ^ 2 배열 자르기 - Lv.2

yujin0517 2023. 10. 11. 18:22

n ^ 2 배열 자르기

 

[문제]

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

 

프로그래머스

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

programmers.co.kr

 

[문제 풀이]

j\i 1 2 3
1 1 2 3
2 2 2 3
3 3 3 3

처음에는 규칙을 찾느라 허덕거렸지만 위의 표를 그린 뒤, 바로 규칙을 찾았다.

더보기

i와 j를 비교해서 더 큰 값을 찾으면 된다!

 

[코드]

class Solution {
    public int[] solution(int n, long left, long right) {
        int len = (int)(right - left) + 1;
        int[] answer = new int[len];
        
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < n; j++) {
                long idx = n * i + j;
                
                if(idx <= right && idx >= left) {
                    answer[(int)(idx - left)] = Math.max(i, j) + 1;
                } 
            }
        }
        
        return answer;
    }
}

이 코드로 제출했을 때는 시간이 어마어마하게 걸렸다....(반 정도가 시간초과)

 

 

이중 for문을 제거하고 제출 성공한 코드 !

class Solution {
    public int[] solution(int n, long left, long right) {
        int[] answer = new int[(int)(right - left) + 1];
        
        for(long l = left; l <= right; l++) {
            int i = (int)(l/n); //row
            int j = (int)(l%n); //col
            
            answer[(int)(l-left)] = Math.max(i, j) + 1; //row, col 중에 큰 값
        }   
        
        return answer;
    }
}