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).
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)
문제대로 재귀 써서 했읍니다
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
오히려 반복문이 좀 더 빠름
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.
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
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 해가면서 하면 좀 더 빠름