栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 第 30 课 914. 卡牌分组 904. 水果成篮

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 第 30 课 914. 卡牌分组 904. 水果成篮

第 30 课
  • [914. 卡牌分组](https://leetcode-cn.com/problems/x-of-a-kind-in-a-deck-of-cards/)
  • [904. 水果成篮](https://leetcode-cn.com/problems/fruit-into-baskets/)

914. 卡牌分组
class Solution:
    def hasGroupsSizeX(self, deck: List[int]) -> bool:        
        d = defaultdict(int)
        for i in deck: d[i] += 1
        x = min(d.values())
        if x == 1:return False        
        for i in range(2, x + 1):
            for j in d.values():
                if j % i: break
            else: return True                
        return False
class Solution {
    public boolean hasGroupsSizeX(int[] deck) {        
        int[] counter = new int[10000]; // 计数
        for (int num: deck) {counter[num]++;}        
        int x = 0; // 迭代求多个数的最大公约数
        for(int cnt: counter) {
            if (cnt > 0) {
                x = gcd(x, cnt); 
                if (x == 1) return false; // 如果某步中gcd是1,直接返回false                
            }
        }
        return x >= 2;
    }    
    // 辗转相除法
    private int gcd (int a, int b) {return b == 0 ? a : gcd(b, a % b);}
}
904. 水果成篮
class Solution:
    def totalFruit(self, fruits: List[int]) -> int:
        d, k, res, left = defaultdict(int), 2, 0, 0
        for i, f in enumerate(fruits):
            if d[f] == 0: k -= 1
            d[f] += 1
            # while k == -1: # 更新 res
            if k < 0: # 不需要 res
                x = fruits[left]
                d[x] -= 1
                if d[x] == 0: k += 1
                left += 1
            #res = max(res, i-left+1)
        #return res
        return len(fruits) - left
class Solution {
    public int totalFruit(int[] fruits) {        
        int n = fruits.length, res = 0, left = 0, k = 2;
        int[] d = new int[n + 1];      
        for (int i = 0; i < n; i++) {
            int x = fruits[i];
            if (d[x] == 0) k--;
            d[x]++;
            while (k == -1) { 
                int y = fruits[left];
                d[y]--;
                if (d[y] == 0) k++;
                left++;
            }
            res = Math.max(res, i - left + 1);
        }
        return res;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/837637.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号