프로그래머스LV0_2

개발자를 꿈꾸는 뚱이·2026년 3월 10일

코딩테스트 스터디

목록 보기
17/39

기록

  • 배열 조각하기
    import java.util.*;
    
    class Solution {
        public int[] solution(int[] arr, int[] query) {
            for(int i = 0; i < query.length; i++){
                int idx = query[i];
                if(i % 2 == 0){
                    arr = Arrays.copyOfRange(arr, 0, query[i] + 1);
                }
                else{
                    arr = Arrays.copyOfRange(arr, query[i], arr.length);
                }
            }
            return arr;
        }
    }
    
    // 좀 더 빠른 방법(매번 배열을 생성하지 않음)
    import java.util.*;
    
    class Solution {
        public int[] solution(int[] arr, int[] query) {
            int start = 0;
            int end = arr.length - 1;
            for(int i = 0; i < query.length; i++) {
                if(i % 2 == 0) {
                    end = start + query[i];
                } 
                else {
                    start = start + query[i];
                }
            }
            return Arrays.copyOfRange(arr, start, end + 1);
        }
    }
처음에 ArrayList로 풀어봤는데 문제 내용에 비해 너무 복잡한 느낌이었다. 찾아보니 Arrays.copyOfRange()라는 함수가 있어 활용하였다.
  • 다항식 더하기
    class Solution {
        public String solution(String polynomial) {
            String answer = "";
            String[] parts = polynomial.split(" ");
            int x = 0, num = 0;
            for(String p : parts){
                if(p.contains("x")){
                    if(p.equals("x")) {
                        x += 1;
                    } else {
                        String co = p.replace("x", ""); 
                        x += Integer.parseInt(co);
                    }
                }
                else{
                    if(!p.equals("+"))  num += Integer.parseInt(p);
                }
            }
            if(num == 0){
                if(x == 1) answer = "x"; 
                else answer = x + "x";
            }
            else if(x == 0){
                answer = Integer.toString(num);
            }
            else{
                if(x == 1) answer = "x + " + num;
                else answer = x + "x + " + num;
            }
            return answer;
        }
    }
split함수를 활용하여 공백 기준으로 분리하여 x 포함 여부로 분기를 나누고 각 항의 값을 구해 값이 0, 1, 나머지를 구분하여 answer를 만들면 된다.
  • 유한소수 판별하기
    class Solution {
        public int solution(int a, int b) {
            int answer = 2;
            int g = gcd(a, b);
            a /= g;
            b /= g;
            while(true){
                if(b % 2 == 0) b /= 2;
                else if(b % 5 == 0) b /= 5;
                else break;
            }
            if(b == 1) answer = 1;
            return answer;
        }
        
        private int gcd(int a, int b){
            while(b != 0){
                int tmp = a % b;
                a = b;
                b = tmp;
            }
            return a;
        }
    }
최대공약수로 기약분수를 만들고 2와 5로 최대한 나눠서 1이 되면 유한소수이고 아니라면 유한소수가 아닌것으로 판단
  • 배열 만들기 2
    import java.util.*;
    
    class Solution {
        public int[] solution(int l, int r) {
            ArrayList<Integer> list = new ArrayList<>();
            for(int i = l; i <= r; i++){
                String s = Integer.toString(i);
                s = s.replace("5", "");
                s = s.replace("0", "");
                if(s.equals("")){
                    list.add(i);
                }
            }
            int[] answer = new int[list.size()];
            if(list.isEmpty()){
                return new int[] {-1};
            }
            for(int i = 0; i < list.size(); i++){
                answer[i] = list.get(i);
            }
            return answer;
        }
    }
l부터 r까지 순회하면 해당 값을 문자열로 바꾸어 5와 0을 모두 지워서 없다면 추가하는 방식으로 해결
  • 저주의 숫자 3
    class Solution {
        public int solution(int n) {
            int answer = 0;
            int num = 1;
            for(int i = 1; i <= n; i++){
                while(num % 3 == 0 || Integer.toString(num).contains("3")){
                    num++;
                }
                answer = num++;
            }
            return answer;
        }
    }
3의 배수만이 아니라 3이 들어가는 경우도 제외해야 하기에 12, 13 같은 경우는 2번을 넘어야 하기에 while문으로 체크하여 num을 늘리는 방식으로 해결
  • 문자열 밀기
    class Solution {
        public int solution(String A, String B) {
            int answer = 0;
            String s = A;
            for(int i = 0; i < A.length(); i++){
                if(B.equals(s)) return answer;
                String a = s.substring(s.length() - 1);
                s = a + s.substring(0, s.length() - 1);
                answer++;
            }
            return -1;
        }
    }
    
    // 개선
    class Solution {
        public int solution(String A, String B) {
            return (B + B).indexOf(A);
        }
    }
substring로 끝부분만 앞으로 붙이는 로직으로 해결하였는데 indexOf를 이용한 더 간단한 방법을 찾았다.
  • 치킨 쿠폰
    class Solution {
        public int solution(int chicken) {
            int answer = 0;
            int left = 0;
            while(chicken != 0){
                chicken += left;
                answer += chicken / 10;
                left = chicken % 10;
                chicken /= 10;
            }
            return answer;
        }
    }
    
    // 개선
    class Solution {
        public int solution(int chicken) {
            if(chicken == 0) return 0;
            return (chicken - 1) / 9;
        }
    }
규칙을 보고 반복문으로 구현했는데 훨씬 간단하게 구현할 수 있는 방법이 있었다.
쿠폰은 10장을 내면 1마리를 주고 서비스 쿠폰이 1장을 받으므로 9장당 치킨 1마리를 먹는 셈(but 마지막은 1장 부족하면 못시키는 것 제외)이라서 공식이 answer=n19\text{answer} = \lfloor \frac{n - 1}{9} \rfloor가 되어 간단하게 해결 가능하다.
  • 등수 매기기
    class Solution {
        public int[] solution(int[][] score) {
            int[] answer = new int[score.length];
            double[] avg = new double[score.length];
            for(int i = 0; i < score.length; i++){
                avg[i] = (double)(score[i][0] + score[i][1]) / 2.0;
            }
            for (int i = 0; i < avg.length; i++) {
                int rank = 1;
                for (int j = 0; j < avg.length; j++) {
                    if (avg[i] < avg[j]) {
                        rank++;
                    }
                }
                answer[i] = rank;
            }
            return answer;
        }
    }
평균을 구해서 각 인덱스의 평균보다 큰 값의 개수를 카운트하여 등수를 매기면 해결
  • 외계어 사전
    class Solution {
        public int solution(String[] spell, String[] dic) {
            for(int i = 0; i < dic.length; i++){
                String word = dic[i];
                if(word.length() != spell.length) continue;
                boolean check = true;
                for(int j = 0; j < spell.length; j++){
                    if(word.contains(spell[j])){
                        word = word.replaceFirst(spell[j], "");
                    }
                    else{
                        check = false;
                        break;
                    }
                }
                if(!check) continue;
                if(word.equals("")) return 1;
            }
            return 2;
        }
    }
replace()를 사용하면 모두 대체해버려 안되는 것도 된다고 할 수 있어 처음 나온 것만 대체하도록 replaceFirst()를 사용하고 모든 spell을 사용하는지 체크하여 해결
  • 로그인 성공?
    class Solution {
        public String solution(String[] id_pw, String[][] db) {
            String id = id_pw[0];
            String pw = id_pw[1];
            for(int i = 0; i < db.length; i++){
                System.out.println(db[i][0] + " " + db[i][1]);
                if(db[i][0].equals(id) && db[i][1].equals(pw)) return "login";
                else if(db[i][0].equals(id) && !db[i][1].equals(pw)) return "wrong pw";
            }
            return "fail";
        }
    }
db 배열을 돌면서 id를 못찾으면 fail을 반환하고 둘 다 같으면 login 반환, pw만 다르면 wrong_pw를 반환하도록 하여 해결
  • 대소문자 바꿔서 출력하기
    import java.util.Scanner;
    
    public class Solution {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String a = sc.next();
            String answer = "";
            for(char c : a.toCharArray()){
                if(Character.isUpperCase(c)){
                    answer += Character.toLowerCase(c);
                }
                else{
                    answer += Character.toUpperCase(c);
                }
            }
            System.out.println(answer);
        }
    }
현재 문자가 대소문자인지 체크하여 변환하여 해결
  • 직사각형 넓이 구하기
    class Solution {
        public int solution(int[][] dots) {
            int answer = 0;
            int min_x = dots[0][0], min_y = dots[0][1];
            int max_x = dots[0][0], max_y = dots[0][1];
            for(int i = 1; i < dots.length; i++){
                min_x = Math.min(dots[i][0], min_x);
                min_y = Math.min(dots[i][1], min_y);
                max_x = Math.max(dots[i][0], max_x);
                max_y = Math.max(dots[i][1], max_y);
            }
            answer = Math.abs(max_x - min_x) * Math.abs(max_y - min_y);
            return answer;
        }
    }
문제가 변이 축과 평행하므로 최소, 최대의 x, y 좌표를 구하면 해결 가능
  • 캐릭터의 좌표
    class Solution {
        public int[] solution(String[] keyinput, int[] board) {
            int to_x = (board[0] - 1)/2, to_y = (board[1] - 1)/2;
            int x = 0, y = 0;
            for(String k : keyinput){
                if(k.equals("up")){
                    if(y + 1 > to_y) continue;
                    y += 1;
                }
                else if(k.equals("down")){
                    if(y - 1 < -to_y) continue;
                    y -= 1;
                }
                else if(k.equals("right")){
                    if(x + 1 > to_x) continue;
                    x += 1;
                }
                else{
                    if(x - 1 < -to_x) continue;
                    x -= 1;
                }
            }
            int[] answer = {x, y};
            return answer;
        }
    }
해당 key에 따라 가로 세로 최대 갈 수 있는 거리를 체크해서 현재 좌표를 갱신하면 해결
  • 종이 자르기
    class Solution {
        public int solution(int M, int N) {
    	       return M * N - 1;
        }
    }
처음 가로나 세로를 자르면 길이 - 1이고 나머지를 자르려면 겹칠 수 없기에 다른 변 길이 (해당 변 - 1)을 하여 2개를 더하면 되므로 이를 공식화 하면 M - 1+ M N - M이므로 M * N - 1을 하면 결과가 됨
  • 전국 대회 선발 고사
    import java.util.*;
    
    class Solution {
        public int solution(int[] rank, boolean[] attendance) {
            ArrayList<Integer> list = new ArrayList<Integer>();
            for(int i = 0; i < rank.length; i++){
                if(attendance[i]){
                    list.add(rank[i]);
                }
            }
            Collections.sort(list);
            int a = 0, b = 0, c = 0;
            for(int i = 0; i < rank.length; i++){
                if(rank[i] == list.get(0)) a = i;
                if(rank[i] == list.get(1)) b = i;
                if(rank[i] == list.get(2)) c = i;
            }
            return a * 10000 + b * 100 + c;
        }
    }
참여 가능한 사람의 등수로 정렬해서 해당 인덱스를 찾아서 해결했는데 for문 2개(중첩 X)에 정렬도 해서 다른 방법을 생각해봤는데 우선순위큐가 괜찮을 거 같은데 아직 자바에서 자료구조를 사용하는 것이 C++처럼 익숙하지 않아 좀 더 공부해야겠다
profile
개발자가 되기 위해 열심히 춤추는 중이에요 🕺

0개의 댓글