LeetCode-575. 分糖果【数组 哈希表】

LeetCode-575. 分糖果【数组 哈希表】

题目描述:

Alice 有 n 枚糖,其中第 i 枚糖的类型为 candyTypei 。Alice 注意到她的体重正在增长,所以前去拜访了一位医生。

医生建议 Alice 要少摄入糖分,只吃掉她所有糖的 n / 2 即可(n 是一个偶数)。Alice 非常喜欢这些糖,她想要在遵循医生建议的情况下,尽可能吃到最多不同种类的糖。

给你一个长度为 n 的整数数组 candyType ,返回: Alice 在仅吃掉 n / 2 枚糖的情况下,可以吃到糖的 最多 种类数。

示例 1:

输入:candyType = 1,1,2,2,3,3

输出:3

解释:Alice 只能吃 6 / 2 = 3 枚糖,由于只有 3 种糖,她可以每种吃一枚。

示例 2:

输入:candyType = 1,1,2,3

输出:2

解释:Alice 只能吃 4 / 2 = 2 枚糖,不管她选择吃的种类是 1,21,3 还是 2,3,她只能吃到两种不同类的糖。

示例 3:

输入:candyType = 6,6,6,6

输出:1

解释:Alice 只能吃 4 / 2 = 2 枚糖,尽管她能吃 2 枚,但只能吃到 1 种糖。

提示:

n == candyType.length

2 <= n <= 104

n 是一个偶数

-105 <= candyTypei <= 105

解题思路一:用一个哈希set记录candyType有多少种糖果,返回Math.min(max_cnt, set.size());

python 复制代码
class Solution {
    public int distributeCandies(int[] candyType) {
        int n = candyType.length;
        int max_cnt = n / 2;
        Set<Integer> set = new HashSet<>();
        for(int i=0;i<n;i++){
            set.add(candyType[i]);
        }
        return Math.min(max_cnt, set.size());
    }
}

时间复杂度:O(n)

空间复杂度:O(n)

解题思路二:简化版

python 复制代码
class Solution {
    public int distributeCandies(int[] candyType) {
        Set<Integer> set = new HashSet<>();
        for(int candy: candyType){
            set.add(candy);
        }
        return Math.min(candyType.length / 2, set.size());
    }
}

时间复杂度:O(n)

空间复杂度:O(n)

解题思路三:

python 复制代码
class Solution:
    def distributeCandies(self, candyType: List[int]) -> int:
        return min(len(set(candyType)), len(candyType) // 2)

时间复杂度:O(n)

空间复杂度:O(n)


创作不易,观众老爷们请留步... 动起可爱的小手,点个赞再走呗 (๑◕ܫ←๑) 欢迎大家关注笔者,你的关注是我持续更博的最大动力

原创文章,转载告知,盗版必究




♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠

相关推荐
祖力551 小时前
Linux应用软件编程:目录IO与framebuffer
linux·运维·算法·framebuffer·目录io
名字还没想好☜2 小时前
Go 用 slices/maps 标准库泛型函数:告别手写 Contains、Sort、去重(Go 1.21)
开发语言·后端·算法·golang·go
地平线开发者2 小时前
【模型轻量化专题】深度学习模型为什么需要轻量化
算法
圣保罗的大教堂2 小时前
leetcode 3622. 判断整除性 简单
leetcode
_Narcissus_2 小时前
链表算法题和静态链表
数据结构·c++·笔记·算法·链表·ai·力扣
Lyyaoo.2 小时前
【普通数组】【中等】除了自身以外数组的乘积
数据结构·算法·leetcode
threerocks2 小时前
《The AI-Native SDLC Playbook》万字拆解
算法·aigc·ai编程
夏玉林的学习之路3 小时前
算法8.环形队列
算法
O。O蛋黄酥啊3 小时前
GraphRAG 和 LightRAG 详解与对比
人工智能·python·算法·rag·graphrag·lightrag
Σίσυφος19003 小时前
depth_from_focus 详解
算法