김태원 8월 특강 정렬

제로베이스 8월 기업 코테 라이브 특강 / 김태원

자바에서 Arrays.sort 함수 사용 예제

1. 기본 배열 오름차순 정렬

int[] nums = {3, 1, 2, 5, 4};
Arrays.sort(nums);
  • nums 배열을 오름차순으로 정렬합니다.

2. 내림차순 정렬

Integer[] tmp = Arrays.stream(nums).boxed().toArray(Integer[]::new);
Arrays.sort(tmp, (a, b) -> b - a);
  • 위 코드에서 int[] 배열을 Integer[]로 변환한 후, 내림차순으로 정렬합니다.
  • 주의: 큰 음수 값의 정렬에서 오류가 발생할 수 있습니다.

3. 좌표 정렬

1) [x, y]에서 x 값에 의한 오름차순 정렬

class Solution {
    public void solution(int[][] nums){
        Arrays.sort(nums, (a, b) -> a[0] - b[0]);
        for(int[] x : nums) System.out.println(x[0] + " " + x[1]);
    }
    
    public static void main(String[] args){
        Solution T = new Solution();
        T.solution(new int[][]{ {1, 2}, {3, 1}, {2, 3}, {1, 5} });
    }
}
  • nums 배열을 x 값에 따라 오름차순으로 정렬합니다.

2) [x, y]에서 y 값에 의한 오름차순 정렬

class Solution {
    public void solution(int[][] nums){
        Arrays.sort(nums, (a, b) -> a[1] - b[1]);
        for(int[] x : nums) System.out.println(x[0] + " " + x[1]);
    }
    
    public static void main(String[] args){
        Solution T = new Solution();
        T.solution(new int[][]{ {1, 2}, {3, 1}, {2, 3}, {1, 5} });
    }
}
  • nums 배열을 y 값에 따라 오름차순으로 정렬합니다.

3) [x, y]에서 x 값에 의한 내림차순 정렬

class Solution {
    public void solution(int[][] nums){
        Arrays.sort(nums, (a, b) -> b[0] - a[0]);
        for(int[] x : nums) System.out.println(x[0] + " " + x[1]);
    }
    
    public static void main(String[] args){
        Solution T = new Solution();
        T.solution(new int[][]{ {1, 2}, {3, 1}, {2, 3}, {1, 5} });
    }
}
  • nums 배열을 x 값에 따라 내림차순으로 정렬합니다.

4) [x, y]에서 x 값에 의한 오름차순 정렬, 단 x 값이 같은 경우 y 값에 따라 내림차순 정렬

class Solution {
    public void solution(int[][] nums){
        Arrays.sort(nums, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);
        for(int[] x : nums) System.out.println(x[0] + " " + x[1]);
    }
    
    public static void main(String[] args){
        Solution T = new Solution();
        T.solution(new int[][]{ {1, 2}, {3, 1}, {2, 3}, {1, 5} });
    }
}
  • x 값이 동일한 경우 y 값에 따라 내림차순으로 정렬합니다.

5) ArrayList 정렬: [x, y]에서 x 값에 의한 오름차순 정렬

class Solution {
    public int solution(int[][] meetings){
        ArrayList<int[]> list = new ArrayList<>();
        for(int[] x : meetings){
            list.add(new int[]{x[0], 1});
            list.add(new int[]{x[1], 2});
        }
        list.sort((a, b) -> a[0] - b[0]);
        // Collections.sort(list, (a, b) -> a[0] - b[0]);
    }
}
  • ArrayList를 사용하여 x 값에 의한 오름차순 정렬을 수행합니다.

4. 이진수 정렬

문제 설명

매개변수 nums에 숫자가 주어지면, nums의 원소들을 이진수로 변환했을 때 1의 개수가 적은 것부터 많은 것 순으로 정렬하는 프로그램을 작성하세요. 1의 개수가 동일한 경우, 십진수로 오름차순 정렬합니다.

입출력 예시

int[] nums = {5, 6, 7, 8, 9};
// 이진수 변환: [101, 110, 111, 1000, 1001]
// 결과: [8, 5, 6, 9, 7]

제한사항

  • nums의 길이는 1,000을 넘지 않습니다.
  • 1 <= nums[i] <= 100,000
import java.util.*;
class Solution {
	public int[] solution(int[] nums){
		int[] answer = new int[nums.length];
		int[][] res = new int[nums.length][2];
		for(int i = 0; i < nums.length; i++){
			int cnt = 0;
			int tmp = nums[i];
			while(tmp > 0){
				cnt += (tmp % 2);
				tmp = tmp / 2;
			}
			res[i][0] = nums[i];
			res[i][1] = cnt;
		}
		Arrays.sort(res, (a, b) -> a[1] == b[1] ? a[0] - b[0] : a[1] - b[1]);
		for(int i = 0; i < res.length; i++){
			answer[i] = res[i][0];
		}
		return answer;
	}

	public static void main(String[] args){
		Solution T = new Solution();
		System.out.println(Arrays.toString(T.solution(new int[]{5, 6, 7, 8, 9})));
		System.out.println(Arrays.toString(T.solution(new int[]{5, 4, 3, 2, 1})));
		System.out.println(Arrays.toString(T.solution(new int[]{12, 5, 7, 23, 45, 21, 17})));
	}
}

카드 가져가기

현수와 영희는 카드 게임을 합니다. 테이블에는 n개의 카드가 있으며, n은 항상 짝수입니다. 각 카드에는 자연수가 적혀 있습니다.

현수와 영희는 한 라운드에 1개의 카드를 각각 가져가며, 총 n/2 라운드를 진행합니다. 이때, 각자가 가져간 카드에 적힌 숫자의 총합이 게임의 점수이며, 점수가 큰 사람이 승리합니다.

현수는 Lady first 정신에 따라 매 라운드 영희가 먼저 카드를 가져가게 합니다. 하지만, 현수는 k번의 우선권을 가지고 있으며, 이 우선권을 사용하는 라운드에서는 현수가 먼저 카드를 가져갈 수 있습니다.

문제 요구사항

매개변수 nums에 각 카드에 적힌 숫자가 주어지고, 매개변수 k에 현수가 우선권을 사용할 수 있는 횟수가 주어지면, 현수가 게임에서 얻을 수 있는 최대 점수를 반환하는 프로그램을 작성하세요. 현수와 영희는 게임에서 이기기 위해 최선을 다합니다.

입출력 예시

nums k answer
[7, 8, 5, 12, 3, 1, 3, 1, 1, 12] 2 28
[8, 2, 12, 12, 12, 12, 2, 2] 2 34
[3, 7, 12, 3, 3, 5, 7, 8, 9, 11, 23, 4, 6, 7] 3 60
[12, 34, 56, 23, 22, 34, 55, 45, 24, 23, 45, 55, 55, 23, 11, 12, 23, 12] 3 283
[14, 15, 20, 11, 10, 20, 20, 12, 9, 22, 27, 25, 30, 19] 3 129

제한사항

  • nums의 길이는 짝수이며, 300,000을 넘지 않습니다.
  • 0 <= k <= n/2
  • 1 <= nums[i] <= 100,000

예제 1번 설명

  1. 1라운드: 영희 12, 현수 12
  2. 2라운드: 영희 8, 현수 7
  3. 3라운드: 영희 3, 현수 5 (우선권 사용)
  4. 4라운드: 영희 1, 현수 3 (우선권 사용)
  5. 5라운드: 영희 1, 현수 1

총합으로 현수의 최대 점수는 28입니다.

import java.util.*;
class Solution {
	public int solution(int[] nums, int k){
		int answer = 0;
		int n = nums.length;
		Integer[] tmp = Arrays.stream(nums).boxed().toArray(Integer[]::new);
		Arrays.sort(tmp, (a, b) -> b - a);
		Integer[] diff = new Integer[n/2];
		for(int i = 0; i < n/2; i++){
			answer += tmp[i*2+1];
			diff[i] = tmp[i*2]-tmp[i*2+1];
		}
		Arrays.sort(diff,(a, b) -> b - a);
		for(int i = 0; i < k; i++){
			answer += diff[i];
		}
		return answer;
	}

	public static void main(String[] args){
		Solution T = new Solution();
		System.out.println(T.solution(new int[]{7, 8, 5, 12, 3, 1, 3, 1, 1, 12}, 2));
		System.out.println(T.solution(new int[]{8, 2, 12, 12, 12, 12, 2, 2}, 2));
		System.out.println(T.solution(new int[]{3, 7, 12, 3, 3, 5, 7, 8, 9, 11, 23, 4, 6, 7}, 3));
		System.out.println(T.solution(new int[]{12, 34, 56, 23, 22, 34, 55, 45, 24, 23, 45, 55, 55, 23, 11, 12, 23, 12}, 3));
		System.out.println(T.solution(new int[]{14, 15, 20, 11, 10, 20, 20, 12, 9, 22, 27, 25, 30, 19}, 3));
	}
}

Leave a comment