guswns1659 / Java-Algorithm

자료구조, 알고리즘 공부 및 문제풀이 저장소

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

20.09.01 - [프로그래머스] K번째수

guswns1659 opened this issue · comments

문제 풀이 핵심 아이디어

  • Arrays.copyOfRange(array, start, end(exclusive))를 이용해서 기본 배열을 자를 수 있는지
  • 인덱스와 몇번째 위치의 차이를 이해할 수 있는지
  • List는 subList(start, end(exclusive))로 구한다.
  • List 역순 정렬은? Collections.sort(list, Collections.reverseOrder());

기본 배열 정렬 : Arrays.sort() 역순 정렬은??

1번. 오름차순 정렬을 한 뒤 뒤 인덱스에서부터 위치를 바꿔준다.

  • 해당 배열을 오름차순 정렬한다.
  • Arrays.copyOf(array, array.length)로 배열을 복사한다. 이유는 원래 배열로하면 인덱스 위치를 기억할 수 없다는 단점
  • 뒤에서부터 반복문을 돌면서 array[(array.length - 1) - index] 위치에 복사한 배열[index] 값을 넣는다.
public class Main {
    public static void main(String[] args) throws IOException {

        int[] array = new int[]{3,1,32,6};
        Arrays.sort(array);
        int[] copyArray = Arrays.copyOf(array, array.length);
        int lastIndex = array.length - 1;

        for (int index = lastIndex; index > -1; index--) {
            array[lastIndex - index] = copyArray[index];
        }

        System.out.println(Arrays.toString(array));
    }
}

2번. 숫자 배열일 경우 -1를 곱해서 구한다.

  • sort()로 정렬한 뒤 -1를 곱한다.
  • sort()로 정렬한 뒤 다시 -1를 곱한다.
import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {

        int[] array = new int[]{3,1,32,6};

        Arrays.sort(array);
        for (int index = 0; index < array.length; index++) {
            array[index] = -1 * array[index];
        }

       Arrays.sort(array);

        for (int index = 0; index < array.length; index++) {
            array[index] = -1 * array[index];
        }

        System.out.println(Arrays.toString(array));
    }
}

어려운점

코드