코테 준비 20일차_9/7

Jieun·2026년 9월 7일

코딩테스트 준비

목록 보기
13/24
  1. 성분으로 구분한 아이스크림 총 주문량
  • 초기 정답
SELECT i.INGREDIENT_TYPE, SUM(h.TOTAL_ORDER) AS TOTAL_ORDER FROM FIRST_HALF h LEFT JOIN ICECREAM_INFO i GROUP BY i.FLAVOR
  • 최종 정답
SELECT i.INGREDIENT_TYPE, SUM(h.TOTAL_ORDER) AS TOTAL_ORDER FROM FIRST_HALF h JOIN ICECREAM_INFO i ON h.FLAVOR = i.FLAVOR GROUP BY i.INGREDIENT_TYPE ORDER BY  TOTAL_ORDER
  1. 같은 숫자는 싫어
    해시맵 쓰면 안되나?
  • 최종 정답
import java.util.*;

public class Solution {
    public int[] solution(int []arr) {
        Stack<Integer> stack = new Stack<>();
        
        for(int num : arr) {
            if(stack.isEmpty() || stack.peek() != num) {
                stack.push(num);
            }
        }
        int[] answer = new int [stack.size()];
        for(int i = answer.length -1;i>=0;i--) {
            answer[i] = stack.pop();
        }
        
    
        return answer;
    }
}

스택이 비어있거나, 맨 위 원소(직전 숫자)와 현재 숫자가 다를 때만 push함
stack.pop()은 뒤에서부터 원소를 꺼내므로, 배열의 맨 뒤 인덱스(answer.length - 1)부터 역순으로 채워넣어야 입력 순서가 유지됨

  • 다른 정답
import java.util.*;

public class Solution {
    public int[] solution(int []arr) {
        ArrayList<Integer> tempList = new ArrayList<Integer>();
        int preNum = 10;
        for(int num : arr) {
            if(preNum != num)
                tempList.add(num);
            preNum = num;
        }       
        int[] answer = new int[tempList.size()];
        for(int i=0; i<answer.length; i++) {
            answer[i] = tempList.get(i).intValue();
        }
        return answer;
    }
}


3. 부족한 금액 계산하기
잔액에서 이용료 제외하고, 또 제외하고 해서 count만큼 반복하면 될거같음

  • 초기 정답
class Solution {
    public long solution(int price, int money, int count) {
        long answer = 0;
        for(int i=1;i<=count;i++) {
            money- price * i;
        }
        if(money > 0) {
            return 0;
        } else {
            return money *-1;
        }

    }
}
  • 최종 정답
class Solution {
    public long solution(int price, int money, int count) {
        long totalCost = 0;
        for(int i=1;i<=count;i++) {
            totalCost += (long) price * i;
        }
       long diff = totalCost - money;
        return diff > 0 ? diff : 0;

    }
}
  • 다른 정답
class Solution {
    public long solution(int price, int money, int count) {
        long totalCost = (long) price * count * (count + 1) / 2;
        return totalCost > money ? totalCost - money : 0;
    }
}

1부터 count까지의 합은 등차수열의 합 공식(n(n+1)2\frac{n(n+1)}{2})을 활용할 수도 있습니다.

profile
비전공자의 백엔드 생존기: 어제보다 1% 더 성장하기

0개의 댓글