티스토리 뷰

https://www.acmicpc.net/problem/17298

 

17298번: 오큰수

첫째 줄에 수열 A의 크기 N (1 ≤ N ≤ 1,000,000)이 주어진다. 둘째 줄에 수열 A의 원소 A1, A2, ..., AN (1 ≤ Ai ≤ 1,000,000)이 주어진다.

www.acmicpc.net

const fs = require('fs');
const [n,arr] = fs.readFileSync("./dev/stdin").toString().trim().split("\n");

class Node{
    constructor(item){
      this.item = item;
      this.next = null;
    }
  }
  
  class Stack{
    constructor(){
      this.topOfStack = null;
      this.length = 0;
    }
  
    push(item){
      const node = new Node(item);
      if(this.topOfStack!=null){
        node.next = this.topOfStack; 
      }
        this.topOfStack = node;
        this.length+=1;
    }
  
    pop(){
      if(this.length==0)return -1;
      const popItem = this.topOfStack;
      this.topOfStack = popItem.next;
      this.length-=1;
  
      return popItem.item
    }
  
    size(){
      return this.length;
    }
  
    empty(){
      if(this.length==0) return 1;
      else return 0;
    }
  
    top(){
      if(this.length==0)return -1;
      return this.topOfStack.item; 
    }
  
  }


const N = +n;
const nums = arr.split(' ').map(v=>+v);
let answer = new Array(N).fill(0);

let stack = new Stack();
for(let i = N-1; i>-1; i--){
    while(answer[i]==0){
        if(stack.size()==0){
            answer[i]=-1;
            stack.push(nums[i])
        }else{
            if(stack.top()<=nums[i]){
                stack.pop();
            }else{
                answer[i]=stack.top();
                stack.push(nums[i])
            }
        }
    }
}

console.log(answer.join(' '))

 

한시간 동안 고민했는데,  안 떠올라서 구글링함^^ 

https://cocoon1787.tistory.com/347

 

[C/C++] 백준 17298번 - 오큰수 (스택)

<코드> #include #include #include using namespace std; int N; stack s; int ans[1000001]; int seq[1000001]; int main() { cin >> N; // 수열 입력받기 for (int i = 0; i < N; i++) cin >> seq[i]; for (i..

cocoon1787.tistory.com

여기 설명이 아주 잘 되어있음...

728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함