[프로그래머스] Lv.1 k번째 수

2024. 5. 2. 13:15·Algorithm/프로그래머스 코딩테스트 문제풀이전략

https://school.programmers.co.kr/learn/courses/30/lessons/42748?language=java

 

프로그래머스

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

programmers.co.kr

 

import java.util.*;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        
        int ans_idx = 0;
        for(int [] command: commands) {
            int start = command[0];
            int end = command[1];
            int target = command[2];
            
            int [] temp = new int[end - start + 1];
            int idx = 0;
            for(int i = start-1; i < end; i++) {
                temp[idx++] = array[i];
            }
            
            Arrays.sort(temp);
            answer[ans_idx++] = temp[target-1];
        }
        return answer;
    }
}

 

Arrays.copyOfRange를 사용한 풀이
import java.util.*;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        
        int ans_idx = 0;
        for(int [] command: commands) {
            int start = command[0] - 1;
            int end = command[1];
            int target = command[2] - 1;
            
            int [] temp = Arrays.copyOfRange(array, start, end);
            Arrays.sort(temp);
            answer[ans_idx++] = temp[target];
        }
        return answer;
    }
}

 

Arrays.copyOfRange(원본 배열, 시작 인덱스, 마지막 인덱스)를 하면 쉽게 배열을 복사할 수 있다.

 

 

'Algorithm > 프로그래머스 코딩테스트 문제풀이전략' 카테고리의 다른 글

[프로그래머스] Lv.2 H-index  (0) 2024.05.02
[프로그래머스] Lv.1 두 개 뽑아서 더하기  (0) 2024.05.02
[프로그래머스] Lv.2 소수 찾기  (0) 2024.04.24
[프로그래머스] Lv.1 모의고사  (0) 2024.04.20
[프로그래머스] Lv.2 모음사전  (0) 2024.04.20
'Algorithm/프로그래머스 코딩테스트 문제풀이전략' 카테고리의 다른 글
  • [프로그래머스] Lv.2 H-index
  • [프로그래머스] Lv.1 두 개 뽑아서 더하기
  • [프로그래머스] Lv.2 소수 찾기
  • [프로그래머스] Lv.1 모의고사
미네구스
미네구스
  • 미네구스
    망구스 blog
    미네구스
  • 전체
    오늘
    어제
    • 분류 전체보기 (174)
      • Kotlin (0)
      • 시큐리티 (0)
        • 개발자 유미 (0)
      • 배포 (4)
      • 회고 (0)
      • Algorithm (142)
        • 프로그래머스 코딩테스트 문제풀이전략 (37)
        • 백준 (65)
        • 프로그래머스 (18)
        • Leetcode (22)
        • 코테 팁 (0)
      • 프로젝트 (8)
        • WEPIK (3)
        • PICK-O (5)
      • CS (1)
        • 운영체제 (5)
        • 네트워크 (1)
        • 면접스터디 (2)
      • 면접 (1)
        • 코테후기 (0)
        • 면접후기 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    백트래킹
    N과 M
    `
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
미네구스
[프로그래머스] Lv.1 k번째 수
상단으로

티스토리툴바