Skip to content

Latest commit

 

History

History
120 lines (94 loc) · 2.53 KB

1381-kir3i.md

File metadata and controls

120 lines (94 loc) · 2.53 KB

1381. Design a Stack With Increment Operation

Solution

  • 시간복잡도: O(Q*M) (Q는 쿼리의 수, M은 maxSize)

  • 알고리즘

    자료구조, 구현

  • 풀이설명

    스택을 구현하면 되는 문제입니다. size에 주의하며 구현하면 됩니다.

  • 소스코드

    • C++

      class CustomStack {
      public:
          int size = 0;
          int maxSize;
          vector<int> data;
          CustomStack(int maxSize) {
              this->maxSize = maxSize;
          }
          
          void push(int x) {
              if (size == maxSize)
                  return;
              data.push_back(x);
              size++;
          }
          
          int pop() {
              if (size == 0)
                  return -1;
              size--;
              int rtn = data.back();
              data.pop_back();
              return rtn;
          }
          
          void increment(int k, int val) {
              if (size <= k)
                  for(int i=0; i<size; i++)
                      data[i] += val;
              else
                  for(int i=0; i<k; i++)
                      data[i] += val;
          }
      };
    • Python

      class CustomStack:
          def __init__(self, maxSize):
              self.size = 0
              self.maxSize = maxSize
              self.data = []
      
          def push(self, x):
              if self.size == self.maxSize:
                  return
              self.data.append(x)
              self.size += 1
      
          def pop(self):
              if self.size == 0:
                  return -1
              self.size -= 1
              return self.data.pop()
      
          def increment(self, k, val):
              if self.size <= k:
                  for i in range(self.size):
                      self.data[i] += val
              else:
                  for i in range(k):
                      self.data[i] += val
    • Java

      class CustomStack {
          public int top = 0;
          public int maxSize;
          public int[] data;
          
          public CustomStack(int maxSize) {
              this.maxSize = maxSize;
              data = new int[maxSize];
          }
          
          public void push(int x) {
              if (top == maxSize)
                  return;
              data[top++] = x;
          }
          
          public int pop() {
              if (top == 0)
                  return -1;
              return data[--top];
          }
          
          public void increment(int k, int val) {
              int sz = k<top? k: top;
              for(int i=0; i<sz; i++)
                  data[i] += val;
          }
      }