返回介绍

solution / 0500-0599 / 0575.Distribute Candies / README_EN

发布于 2024-06-17 01:03:59 字数 3192 浏览 0 评论 0 收藏 0

575. Distribute Candies

中文文档

Description

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_.

 

Example 1:

Input: candyType = [1,1,2,2,3,3]
Output: 3
Explanation: Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.

Example 2:

Input: candyType = [1,1,2,3]
Output: 2
Explanation: Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types.

Example 3:

Input: candyType = [6,6,6,6]
Output: 1
Explanation: Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.

 

Constraints:

  • n == candyType.length
  • 2 <= n <= 104
  • n is even.
  • -105 <= candyType[i] <= 105

Solutions

Solution 1

class Solution:
  def distributeCandies(self, candyType: List[int]) -> int:
    return min(len(candyType) >> 1, len(set(candyType)))
class Solution {
  public int distributeCandies(int[] candyType) {
    Set<Integer> s = new HashSet<>();
    for (int c : candyType) {
      s.add(c);
    }
    return Math.min(candyType.length >> 1, s.size());
  }
}
class Solution {
public:
  int distributeCandies(vector<int>& candyType) {
    unordered_set<int> s;
    for (int c : candyType) s.insert(c);
    return min(candyType.size() >> 1, s.size());
  }
};
func distributeCandies(candyType []int) int {
  s := hashset.New()
  for _, c := range candyType {
    s.Add(c)
  }
  return min(len(candyType)>>1, s.Size())
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文