관리 메뉴

Tree's 개발일기

[자바] 최솟값 만들기 본문

문제풀이/프로그래머스

[자바] 최솟값 만들기

tree0123 2023. 8. 10. 23:07
728x90

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

 

프로그래머스

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

programmers.co.kr

int배열을 Integer배열로 바꿔서 내림차순으로 정렬하고, 오름차순 정렬한 것과 곱한 값을 차례로 더하는 방식으로 했더니, 효율성 테스트에서 시간초과가 났다.

import java.util.*;
class Solution
{
    public int solution(int []A, int []B)
    {
        int answer = 0;
        Arrays.sort(A);
        Integer[] B_arr = Arrays.stream(B).boxed().toArray(Integer[]::new);
        Arrays.sort(B_arr, Collections.reverseOrder());
        
        for (int i=0; i<A.length; i++) {
            answer+=(A[i]*B_arr[i]);
        }
        
        return answer;
    }
}

그래서 다른 사람들이 priorityQueue를 사용하면, 효율성 테스트를 통과할 수 있다는 힌트를 얻고

구현했다. (반대는 Collections.reveseOrder()사용해서 구현)

import java.util.*;
class Solution
{
    public int solution(int []A, int []B)
    {
        int answer = 0;
        PriorityQueue<Integer> pq = new PriorityQueue<>();
         PriorityQueue<Integer> pq2 = new PriorityQueue<>(Collections.reverseOrder());
        for (int i=0; i<A.length; i++) {
            pq.add(A[i]);
            pq2.add(B[i]);
        }
        
        for (int i=0; i<A.length; i++) {
            answer+=(pq.poll()*pq2.poll());
        }
        
        return answer;
    }
}
728x90

'문제풀이 > 프로그래머스' 카테고리의 다른 글

[자바] 피보나치 수  (0) 2023.08.14
[자바] [1차] 캐시  (0) 2023.08.12
[자바]N개의 최소공배수  (0) 2023.07.29
[자바] 방금그곡  (0) 2023.07.29
[자바] 타겟넘버  (0) 2023.07.29
Comments