Leetcode 575. Distribute Candies

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Distribute Candies

2. Solution

解析:Version 1,使用dict。

  • Version 1
1
2
3
4
5
6
7
class Solution:
def distributeCandies(self, candyType: List[int]) -> int:
candies = {}
for candy in candyType:
candies[candy] = candies.get(candy, 0) + 1
return min(len(candies), len(candyType) // 2)
# return min(len(Counter(candyType)), len(candyType) // 2)

解析:Version 2,使用set。

  • Version 2
1
2
3
4
5
6
7
class Solution:
def distributeCandies(self, candyType: List[int]) -> int:
candies = set()
for candy in candyType:
candies.add(candy)
return min(len(candies), len(candyType) // 2)
# return min(len(set(candyType)), len(candyType) // 2)

Reference

  1. https://leetcode.com/problems/distribute-candies/
如果有收获,可以请我喝杯咖啡!