프로그래머스 문제

 

프로그래머스

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

programmers.co.kr

스택 카테코리에 있지만, ArrayList로 풀었다.

 

🐾풀이 방식

Math.ceil((double)(100-progress[i])/(double)speed[i]) 을 이용하여 나머지 값을 올림하여 list 에 추가해주었다.

나는 return 값을 염두해 두고 풀어서 좀 지저분하게 푼 것 같다.

 

다른 사람들의 경우

int progressed=-1;
progresses[i] + (progressed*speeds[i]) < 100

를 사용한 듯하다. 좋은 식이다.

 

코드

import java.util.*;
class Solution {
    public int[] solution(int[] progresses, int[] speeds) {
        int[] answer = {};
        List<Integer> list = new ArrayList<>();
        double finDay=Math.ceil((double)(100-progresses[0])/(double)speeds[0]); 
        int progressed=1;
        
        for(int i=1; i<progresses.length; i++) {
            double nowDay = Math.ceil((double)(100-progresses[i])/(double)speeds[i]);
            if(finDay >= nowDay) { // 전일 완료 일자가 당일 완료일자보다 클 때,
                progressed++;
               
            } 
            else if(finDay < nowDay) {  
                list.add(progressed);
                finDay=nowDay; // 몇일 걸리면 끝나는지.
                progressed=1;
            }
            if(i==(progresses.length-1)) list.add(progressed);
        }
        return list.stream()
	           .mapToInt(Integer::intValue)
    	       .toArray();
    }
}

 

 

🦉 Double Colon

자료 구조를 ArrayList를 사용한 이유는 Array로 반환하기 쉽겠다 싶어서 였는데, 생각보다 쉽진 않았다.

더블콜론도 처음 써봤다.

클래스를 직접 사용하여 메소드 참조, 호출을 한다.

 

<class name> :: <mathod name>

 

 

import java.util.stream.*; 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        // Get the stream 
        Stream<String> stream 
            = Stream.of("Geeks", "For", 
                        "Geeks", "A", 
                        "Computer", 
                        "Portal"); 
  
        // Print the stream 
        // using double colon operator 
        stream.forEach(System.out::println); 
    } 
}

 

 

참조

Double colon

'Algorithm > Programmers' 카테고리의 다른 글

프로그래머스 (Java) - [1차] 캐시, LRU 알고리즘  (2) 2024.06.13

프로그래머스 문제

 

프로그래머스

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

programmers.co.kr

LRU 캐시에 대한 문제이다.

 

🐾 풀이 방식

Queue를 이용하여 풀었다.

현재 Queue 안의 size와 cacheSize를 비교해서 제거하는 것 까지 생각해내는 것이 중요한 듯 싶다.

LRU 알고리즘을 제대로 이해하지 못해서 정말 헤맸었는데 코드 힌트를 보고 다시 공부했다.

 

 

코드

import java.util.*;
class Solution {
    public int solution(int cacheSize, String[] cities) {
        int answer = 0;
        if(cacheSize==0) return cities.length*5;    
        Queue<String> cache = new LinkedList<>();
        
        for(String city : cities) {
            String lowCity = city.toLowerCase();
            if(cache.contains(lowCity)) { // 캐시에 있다면
                cache.remove(lowCity);
                cache.add(lowCity);
                answer+=1;
            } else { // 캐시에 없다면
                if(cache.size()==cacheSize) { // 캐시 사이즈가 찼으면
                    cache.poll(); // 캐시 pop
                }
                // 캐시 공간이 여유로우면
                cache.add(lowCity);
                answer+=5;
            }
            
        }
        return answer;
    }
}

 

 

 

🦉 LRU 알고리즘

간단하게 생각하면 되는데 알고리즘에 대한 궁금증이 생겼다.

cacheSize=5, cities={a, b, c, b, d, e, f}; 일때 LRU 알고리즘을 사용하게 되면

절차가 {a}, {a, b}, {a, b, c}로 쌓다가 a를 pop하고 {b, c, b}가 되는지 아니면 {a, b} 두개를 pop하고 {c, b} 부터 되는지가 궁금했다.

 

▶ Chat GPT에게 알아본 결과 LRU 지식을 잘못 이해한 것이었다.

아싸에게 너무나 감사한 선생님이다..

ChatGPT 질문 결과

 

내가 헷갈리는 부분을 명확히 짚어줬다.

중복 값이 나오면 해당 index 부터 시작하는 것이 아니라 해당 값을 맨 뒤로 이동시키는 것이 관건이다.

 

 

참조

참조한 코드

'Algorithm > Programmers' 카테고리의 다른 글

프로그래머스 (Java) - 기능개발  (0) 2024.06.25

+ Recent posts