View

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

프로그래머스

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

programmers.co.kr

📚 문제

배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.
예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면

  1. array의 2번째부터 5번째까지 자르면 [5, 2, 6, 3]입니다.
  2. 1에서 나온 배열을 정렬하면 [2, 3, 5, 6]입니다.
  3. 2에서 나온 배열의 3번째 숫자는 5입니다.

배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 return 하도록 solution 함수를 작성해주세요.
 

💻 코드

import java.util.ArrayList;
import java.util.Collections;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];

        for(int i=0; i< commands.length; i++){
            ArrayList<Integer> answerList = new ArrayList<>();
            for(int j=commands[i][0]-1; j<commands[i][1]; j++) answerList.add(array[j]);
            Collections.sort(answerList);
            answer[i] = answerList.get(commands[i][2]-1);
        }
        return answer;
    }
}

 
+) 제일 좋아요 많은 코드

1.Arrays.copyOfRange(원본 배열,복사하려는 시작 요소의 인덱스,복사하려는 마지막 요소의 인덱스의 바로 다음 인덱스)

: 특정 배열의 원하는 범위만큼 복사하여 새로운 배열을 만드는 메소드함수

int[] temp = Arrays.copyOfRange(array,commands[i][0]-1, commands[i][1]);

 
2. Array(배열)과 ArrayList(리스트)의 차이

  ArrayArrayList
 사이즈 초기화시 고정
int[] myArray = new int[6];


초기화시 사이즈를 표시하지 않음. 유동적
ArrayList<Integer> myArrayList = new ArrayList<>();


 속도 초기화시 메모리에 할당되어 속도가 빠르다.추가시 메모리를 재할당하여 속도가 느리다.
 변경 사이즈 변경 불가 추가 삭제 가능
add(), remove() 로 가능
 다차원 가능
int[][][] muttiArray = new int [3][3][3];
 불가능

구글링하다가 찾은 배열과 리스트의 차이점을 한눈에 파악할 수 있는 표
(출처 : https://blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=sangrime&logNo=220622445166) 

728x90
Share Link
reply
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31