23년 8월 2일 [알고리즘 - sorting & thinking]

sua·2023년 8월 2일
0

알고리즘 가보자고

목록 보기
69/101

인프런 이진수 정렬

문제

나의 풀이

import java.util.Arrays;

public class BinarySort {
    public static 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 count = 0;
            int tmp = nums[i];
            while(tmp > 0) {
                count += (tmp % 2); // 1의 개수 구하기
                tmp /= 2;
            }
            res[i][0] = nums[i];
            res[i][1] = count;
        }

        Arrays.sort(res, (a, b) -> a[1] == b[1] ? a[0] - b[0] : a[1] - b[1]); // 1의 개수로 정렬. 같으면 십진수 기준 오름차순으로
        for(int i = 0; i < res.length; i++) {
            answer[i] = res[i][0];
        }
        return answer;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(BinarySort.solution(new int[]{5, 6, 7, 8, 9})));
    }
}

결과


인프런 수열 찾기

문제

나의 풀이

import java.util.*;

public class FindSequence {
    public static int[] solution(int[] nums) {
        int answer[] = new int[nums.length / 2];
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int x : nums) {
            map.put(x, map.getOrDefault(x, 0) + 1);
        }
        Arrays.sort(nums); // 오름차순 정렬
        int index = 0;
        for(int x : nums) {
            if(map.get(x) == 0) { // 개수가 0이면 이미 지워진 것이므로 패스
                continue;
            }
            answer[index] = x; // 현재 배열에서 가장 작은 수 answer에 넣기
            index++;
            map.put(x, map.get(x) - 1); // 가장 작은 수의 개수 1 빼기
            map.put(x * 2, map.get(x * 2) - 1); // 가장 작은 수에 2배한 값의 개수 1 빼기
        }
        return answer;
    }
    public static void main(String[] args) {
        System.out.println(Arrays.toString(FindSequence.solution(new int[]{14, 4, 2, 6, 3, 10, 10, 5, 5, 7, 7, 14})));
    }
}

nums에 남은 수 중에 가장 작은 값을 2배한 값을 둘 다 지워주는 것을 반복해서 원래 수열을 찾아준다. 반복하며 남은 수 중에 가장 작은 값들을 answer의 원소로 추가하면 된다.

결과

profile
가보자고

0개의 댓글