[Mock] Microsoft 2

shsh·2021년 3월 12일
0

Mock

목록 보기
7/93

1185. Day of the Week

Given a date, return the corresponding day of the week for that date.

The input is given as three integers representing the day, month and year respectively.

Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}.

My Answer 1: Accepted (Runtime: 32 ms - 58.98% / Memory Usage: 14.4 MB - 24.48%)

import datetime

class Solution:
    def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
        days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
        n = datetime.date(year, month, day).weekday()
        
        return days[n]

이거 datetime 안쓰면.. 지금 요일 기준으로 윤년까지 계산하고........
달마다 날짜가 다른.. (3월 -> 31일, 4월 -> 30일) 그런 거까지 다 고려해야하는거 같아서
걍.... 이대로 외우기로 결심했읍니다.


232. Implement Queue using Stacks

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).

Implement the MyQueue class:

  • void push(int x) Pushes element x to the back of the queue.
  • int pop() Removes the element from the front of the queue and returns it.
  • int peek() Returns the element at the front of the queue.
  • boolean empty() Returns true if the queue is empty, false otherwise.

Notes:

  • You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.

Follow-up: Can you implement the queue such that each operation is amortized O(1) time complexity? In other words, performing n operations will take overall O(n) time even if one of those operations may take longer.

My Answer 1: Accepted (Runtime: 28 ms - 79.78% / Memory Usage: 14.5 MB - 11.81%)

class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.stack = []

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.stack.append(x)

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        return self.stack.pop(0)

    def peek(self) -> int:
        """
        Get the front element.
        """
        return self.stack[0]

    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        if self.stack:
            return False
        return True


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

하라는대로 했다
고 생각했는데... stack 2개 쓰는 거였음;

My Answer 2: Accepted (Runtime: 28 ms - 79.78% / Memory Usage: 14.1 MB - 98.71%)

class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.stack1 = []
        self.stack2 = []

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.stack1.append(x)

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        for i in range(len(self.stack1)):
            self.stack2.append(self.stack1.pop())
        result = self.stack2.pop()
        for i in range(len(self.stack2)):
            self.stack1.append(self.stack2.pop())
        return result

    def peek(self) -> int:
        """
        Get the front element.
        """
        return self.stack1[0]

    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        if self.stack1:
            return False
        return True


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

도대체 왜 stack 두개를 쓰나 모르겠어서 루션이 살짝 참고함..^^

pop(0) 이런 거 안되고 pop() 만 써야 하나봄... 오직 top 만

only push to top, peek/pop from top,

size, and is empty operations are valid

그래서 pop 할 때, stack1 에 있는 값을 모두 stack2 로 옮기고 => stack1 거꾸로 = stack2

그 때의 stack2.pop() 값이 처음 stack1[0] 값이니까 result 에 넣고 return

다시 stack1 원상복귀한 후 return result

peek 도 마찬가지로 하기도 하덥디다...

profile
Hello, World!

0개의 댓글

Powered by GraphCDN, the GraphQL CDN