보라코딩

프로그래머스 자바 :: Stack / Queue 본문

프로그래머스 (java)

프로그래머스 자바 :: Stack / Queue

new 보라 2023. 11. 20. 21:11
Stack 

 

Stack<Integer> stack = new Stack<>();

// 요소 추가
stack.push(1);

// 요소 제거(꺼내기)
stack.pop();

// 스택 비우기
stack.clear();

// 스택 크기 체크
stack.size();

// 스택 비어있는지 유무 확인
stack.empty();

// 스택에 요소 존재하는지 확인
stack.contains(1);

// 스택 최상단 요소 확인, pop()과 다름
stack.peek();

 

 

 

 

Queue 

 

Queue<Integer> queue = new LinkedList<>();

// 큐에 요소 추가
queue.add(1);       // 예외발생
queue.offer(2);      // false리턴

// 큐에서 요소 제거
queue.remove();    // 예외 발생
queue.pool();         // null 리턴

// 큐 비우기
queue.clear();

// 큐의 최전방 요소 확인
queue.element();    // 예외 발생
queue.peek();         // null 리턴

 

 

 

 


같은 숫자는 싫어

 

 

 

 

 

내 풀이

 

맨 처음에 일단 stack에 넣고

peek으로 확인해서 동일하면 넣지 않고

다르면 넣게 했다.

 

답은 array로 return 해야 했는데

stream 사용하고 싶어서 stack에서 바로 array로 리턴하는 법을 배웠다.

 

import java.util.*;

public class Solution {
    public int[] solution(int []arr) {
        //int[] answer = {};
                
        Stack<Integer> stack = new Stack<>();

        for (int a : arr) {
          if (stack.empty()) {
            stack.push(a);
          } else if (stack.peek() == a) {

          } else {
            stack.push(a);
          }
        }               
        return stack.stream().mapToInt(Integer::intValue).toArray();
    }
}

 

 

 

다른사람 풀이

 

...? return 타입을 stack으로 바꿔도 되나?

여튼 엄청 심플해서 마음에 든다.

import java.util.*;

public class Solution {
    public Stack<Integer> solution(int []arr) {

        Stack<Integer> stack = new Stack<>();

        for(int num : arr){
            if(stack.size() == 0 || stack.peek() != num){
                stack.push(num);
            }
        }



        return stack;
    }
}

 

 

 

 

 


기능 개발

 

 

 

 

 

 

내 풀이

 

넣은 순서대로 확인해야 해서 이번에는 Queue 사용했다.

무작정 queue.peek()을 사용하면 안되고 isEmpty()로 체크를 해줘야 한다.

 

pop을 한 데이터는 비교 시 사용하려면  변수에 넣어두는 것이 좋다.

import java.util.*;

class Solution {
    public int[] solution(int[] progresses, int[] speeds) {
        //int[] answer = {};
        
       Queue<Integer> queue = new LinkedList<>();

        for (int i = 0; i < speeds.length; i++) {
          if ((100 - progresses[i]) % speeds[i] == 0) {
            queue.add((100 - progresses[i]) / speeds[i]);
          } else {
            queue.add(((100 - progresses[i]) / speeds[i]) + 1);
          }
        }

        List<Integer> list = new ArrayList<>();

        while (!queue.isEmpty()) {
          int count = 1;
          int top = queue.remove();

          while (!queue.isEmpty() && queue.peek() <= top) {
            queue.remove();
            count++;
          }
          list.add(count);
        }       
        
        return list.stream().mapToInt(Integer::intValue).toArray();
    }
}

 

 

 

 

 

 


올바른 괄호

 

 

 

 

 

내 풀이

 

처음에는 (이면 ++ 하고 )이면 --로 풀었는데

코드 실행은 성공하나 채점하면 몇문제 틀리고 성능 통과를 못했다.

 

Stack<Character> stack = new Stack<>();

for문 돌려서 charAt으로  '(' 이면 stack에 넣고 ')' 이면 빼고 isEmpty()로 확인하여 해결

 

진행 중 stack 비어있을 수도 있어서 예외처리로 false

 

import java.util.*;

class Solution {
    boolean solution(String s) {
        boolean answer = true;
        
        Stack<Character> stack = new Stack<>();
        
        try{
          for(int i = 0; i< s.length(); i++){
              if(s.charAt(i) == '(') {
                stack.push('(');
              } else if (s.charAt(i) == ')'){
                stack.pop();
              }
            }
        } catch(Exception e){
              answer = false;
        }      

        if(!stack.isEmpty()){
          answer = false;
        }        
        return answer;
    }
}

 

 

 

다른 사람 풀이

 

내가 기존에 풀려고 했던 ++, -- 방식!

 

class Solution {
    boolean solution(String s) {
        boolean answer = false;
        int count = 0;
        for(int i = 0; i<s.length();i++){
            if(s.charAt(i) == '('){
                count++;
            }
            if(s.charAt(i) == ')'){
                count--;
            }
            if(count < 0){
                break;
            }
        }
        if(count == 0){
            answer = true;
        }

        return answer;
    }
}

 

 

 


프로세스

 

 

 

 

 

 

내 풀이

 

푸는데 꽤나 오래 걸렸다.

 

새롭게 배운 점은  PriorityQueue 가 존재한다는 사실!

 

//낮은 숫자가 우선 순위인 int 형 우선순위 큐 선언
PriorityQueue<Integer> priorityQueueLowest = new PriorityQueue<>();

//높은 숫자가 우선 순위인 int 형 우선순위 큐 선언
PriorityQueue<Integer> priorityQueueHighest = new PriorityQueue<>(Collections.reverseOrder());

 

 

 

import java.util.*;

class Solution {
    public int solution(int[] priorities, int location) {
        int answer = 0;
        PriorityQueue<Integer> queue = new PriorityQueue<>(Collections.reverseOrder());

        for(int num : priorities) {
queue.add(num);
}
        
while(!queue.isEmpty()) {
for(int i = 0; i < priorities.length; i++) {
if(priorities[i] == queue.peek()) {
queue.poll();
answer++;
if(i == location)
return answer;
}
}
}  
        return answer;
    }
}

 

 

 


 

다리를 지나는 트럭

 

 

와 어렵..

이건 잠시 포기... ㅠ

 

 

[스택/큐] 다리를 지나는 트럭 - Java코드 ★★★

https://programmers.co.kr/learn/courses/30/lessons/42583 코딩테스트 연습 - 다리를 지나는 트럭 트럭 여러 대가 강을 가로지르는 일차선 다리를 정해진 순으로 건너려 합니다. 모든 트럭이 다리를 건너려면

bangu4.tistory.com

 

 

 


 

주식가격

 

 

 

 

 

 

내 풀이

 

문제가 처음에 잘 이해가 되지 않았는데

이해하고 나니 금방 풀었다.

다만 문제는 스택/큐를 사용하지 않음...ㅋㅋ

 

이건 다시 공부할 것!

 

import java.util.*;


class Solution {
    public int[] solution(int[] prices) {        
        int[] answer = new int[prices.length];

        for (int i = 0; i < prices.length; i++) {
          int count = 0;
          for (int j = i + 1; j < prices.length; j++) {
            if (prices[i] <= prices[j]) {
              count++;
            }
            if (prices[i] > prices[j]) {
              count++;
              break;
            }
          }
          answer[i] = count;
        }
        
        return answer;
    }
}

 

 

 

다른 사람 풀이

 

stack 사용!

 

 

 

class Solution {
    public int[] solution(int[] prices) {
        int[] ans = new int[prices.length];
        Stack<Integer> stack = new Stack();

        for (int i = 0; i < prices.length; i++) {
            while (!stack.isEmpty() && prices[i] < prices[stack.peek()]) {
                ans[stack.peek()] = i - stack.peek();
                stack.pop(); // 답을 구했기 때문에 stack에서 제거한다
            }
            stack.push(i);
        }

        while (!stack.isEmpty()) { // 값을 구하지 못한 index == 끝까지 가격이 떨어지지 않은 주식
            ans[stack.peek()] = prices.length - stack.peek() - 1;
            stack.pop();
        }
        return ans;
    }
}