[Mock] Microsoft 5

shsh·2021년 3월 31일
0

Mock

목록 보기
19/93

509. Fibonacci Number

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.

Given n, calculate F(n).

My Answer 1: Accepted (Runtime: 844 ms - 18.76% / Memory Usage: 14.3 MB - 9.26%)

class Solution:
    def fib(self, n: int) -> int:
        def func(n):
            if n == 0:
                return 0
            if n == 1:
                return 1
            return func(n-1) + func(n-2)
        
        return func(n)

문제대로 재귀 써서 했읍니다

My Answer 2: Accepted (Runtime: 792 ms - 66.23% / Memory Usage: 15.8 MB - 96.31%)

class Solution:
    def fib(self, n: int) -> int:
        if n == 0:
            return 0
        
        a = 0
        b = 1
        result = 1
        for i in range(1, n):
            result = a + b
            a = b
            b = result
        
        return result

오히려 반복문이 좀 더 빠름


575. Distribute Candies

Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor.

The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice.

Given the integer array candyType of length n, return the maximum number of different types of candies she can eat if she only eats n / 2 of them.

My Answer 1: Accepted (Runtime: 800 ms - 53.96% / Memory Usage: 16 MB - 94.48%)

class Solution:
    def distributeCandies(self, candyType: List[int]) -> int:
        total = len(candyType) // 2
        
        count = collections.Counter(candyType)
        
        if total > len(count):
            return len(count)
        
        return total

n / 2 와 different type 의 개수 count 를 비교해서 return

My Answer 2: Accepted (Runtime: 792 ms - 66.23% / Memory Usage: 15.8 MB - 96.31%)

class Solution:
    def distributeCandies(self, candyType: List[int]) -> int:
        total = len(candyType) // 2
        
        count = {}
        
        cnt = 0
        for candy in candyType:
            if candy not in count:
                cnt += 1
                count[candy] = 1
            if cnt > total:
                return total
        
        if total > cnt:
            return cnt
        
        return total

직접 count 해가면서 하면 좀 더 빠름

profile
Hello, World!

0개의 댓글

Powered by GraphCDN, the GraphQL CDN