+1 2022 KAKAO TECH INTERNSHIP 두 큐 합 같게 만들기

이동한·2023년 6월 12일
0

알고리즘 기출

목록 보기
4/22

아이디어: 1.두 큐를 모두 바라 보는게 아니라 하나의 큐만 바라봐서 전체합의 반이 돼는지 점검
2. 두 큐 원소합의 두 배 이상이 되면 한 바퀴 돌린것과 같아서 종료조건이다.

import java.util.*;

class Solution {
    public int solution(int[] queue1, int[] queue2) {
        int answer = -2;
        Queue<Integer> q1 = new LinkedList<>();
        Queue<Integer> q2 = new LinkedList<>();
        long totalSum =0;
        long target = 0;
        long q1Sum = 0;
        
        for (int i=0; i< queue1.length; i++){
            totalSum+=queue1[i];
            totalSum+=queue2[i];
            q1Sum+=queue1[i];
            q1.offer(queue1[i]);
            q2.offer(queue2[i]);
        }
        if(totalSum%2 != 0) return -1;
        
        target = totalSum/2;
        int cnt = 0;
        
        while(true) {
            if(cnt > (queue1.length+queue2.length)*2) return -1;
            if(q1Sum == target) break;
            else if(q1Sum>target){
                q1Sum -= q1.peek();
                q2.offer(q1.poll());
            }else{
                q1Sum+=q2.peek();
                q1.offer(q2.poll());
            }
            cnt++;
        }
        return cnt;
    }
}

배운점:
Queue = new LinkedList

두번째

import java.util.*;

class Solution {
    public int solution(int[] queue1, int[] queue2) {
        Queue<Integer> q1 = new LinkedList<>();
        Queue<Integer> q2 = new LinkedList<>();
        
        long tot = 0;
        long q1Tot = 0;
        for(int i=0; i<queue1.length; i++){
            tot+= (queue1[i]+queue2[i]);
            q1Tot+=queue1[i];
            q1.offer(queue1[i]);
            q2.offer(queue2[i]);
        }
        if(tot%2 == 1) return -1;
        
        int cnt = 0;
        long target = tot/2;
        while (true){
            if(cnt > (queue1.length+queue2.length)*2) return -1; // 전체 원소 두배 만큼 돌았을때 갱신 안되면 fail
            if(q1Tot == target) break;
            
            // 매번 갱신된 큐의 값을 합하는 것은 너무 많은 시간 소모
            
            else if(q1Tot > target){
                q1Tot -= q1.peek();
                q2.offer(q1.poll());
            }else{
                if(q2.isEmpty()) return -1;
                q1Tot += q2.peek();
                q1.offer(q2.poll());
            }
            cnt++;
        }
        return cnt;
    }
}

변수에 할당해야할 타입 잘 보자: 이번의 경우 int 로 큐의 합과 타깃을 지정하면 런타임에러및
오류가 발생한다: int -> long
Queue의 구현체는 LinkedList<>();
Queue메서드 :
삽입: q.offer()
leftpop: q.poll()
peek : q.peek()
isEmpty: q.isEmpty()
그리디:
특정기준(q1의 합이 반 이상인지 아닌지)로 갱신하기

profile
Pragmatic, Productive, Positivist

0개의 댓글