Leetcode刷题 2021.02.10

Leetcode846 一手顺子

爱丽丝有一手(hand)由整数数组给定的牌。

现在她想把牌重新排列成组,使得每个组的大小都是 W,且由 W 张连续的牌组成。

如果她可以完成分组就返回 true,否则返回 false。

等会儿要回家过年了,不想断更,先记录一下吧。晚上或者明天再写思路和注释。

class Solution {
    
    
    public boolean isNStraightHand(int[] hand, int W) {
    
    
        int n = hand.length;
        if (n % W != 0) return false;
        TreeMap<Integer, Integer> map = new TreeMap<>();

        for(int h : hand){
    
    
            map.put(h, map.getOrDefault(h, 0) + 1);
        }

        while (!map.isEmpty()){
    
    
            int temp = map.firstKey();
            for(int i = temp; i < temp + W; i++){
    
    
                if (!map.containsKey(i)) return false;
                map.put(i, map.get(i) - 1);
                if (map.get(i) == 0) map.remove(i);
            }
        }

        return true;
    }
}

Leetcode1276 不浪费原料的汉堡制作方案

圣诞活动预热开始啦,汉堡店推出了全新的汉堡套餐。为了避免浪费原料,请你帮他们制定合适的制作计划。

给你两个整数 tomatoSlices 和 cheeseSlices,分别表示番茄片和奶酪片的数目。不同汉堡的原料搭配如下:

巨无霸汉堡:4 片番茄和 1 片奶酪
小皇堡:2 片番茄和 1 片奶酪
请你以 [total_jumbo, total_small]([巨无霸汉堡总数,小皇堡总数])的格式返回恰当的制作方案,使得剩下的番茄片 tomatoSlices 和奶酪片 cheeseSlices 的数量都是 0。

如果无法使剩下的番茄片 tomatoSlices 和奶酪片 cheeseSlices 的数量为 0,就请返回 []。

class Solution {
    
    
    public List<Integer> numOfBurgers(int tomatoSlices, int cheeseSlices) {
    
    
        List<Integer> res = new ArrayList<>();
        if (tomatoSlices % 2 != 0 || cheeseSlices > tomatoSlices) return res;
        double temp = (tomatoSlices - 2 * cheeseSlices) / 2;
        if (temp > Math.floor(temp)){
    
    
            return res;
        }
        int x = (int) temp;
        if (x < 0 || cheeseSlices - x < 0) return res;
        res.add(x);
        res.add(cheeseSlices - x);
        return res;
    }
}

Leetcode983 最低票价

在一个火车旅行很受欢迎的国度,你提前一年计划了一些火车旅行。在接下来的一年里,你要旅行的日子将以一个名为 days 的数组给出。每一项是一个从 1 到 365 的整数。

火车票有三种不同的销售方式:

一张为期一天的通行证售价为 costs[0] 美元;
一张为期七天的通行证售价为 costs1 美元;
一张为期三十天的通行证售价为 costs2 美元。
通行证允许数天无限制的旅行。 例如,如果我们在第 2 天获得一张为期 7 天的通行证,那么我们可以连着旅行 7 天:第 2 天、第 3 天、第 4 天、第 5 天、第 6 天、第 7 天和第 8 天。

返回你想要完成在给定的列表 days 中列出的每一天的旅行所需要的最低消费。

class Solution {
    
    
    public int mincostTickets(int[] days, int[] costs) {
    
    
        int[] dp = new int[366];
        Set<Integer> set = new HashSet<>();
        for(int day : days){
    
    
            set.add(day);
        }
        
        for(int i = 1; i < dp.length; i++){
    
    
            if (i > days[days.length - 1]) break;
            if (!set.contains(i)){
    
    
                dp[i] = dp[i - 1];
            }else{
    
    
                dp[i] = Math.min(dp[i - 1] + costs[0], Math.min(dp[Math.max(0, i - 7)] + costs[1], dp[Math.max(0, i - 30)] + costs[2]));
            }
        }

        return dp[days[days.length - 1]];
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43447128/article/details/113779626