[leetcode刷题]——贪心思想

时间:2021-06-12
本文章向大家介绍[leetcode刷题]——贪心思想,主要包括[leetcode刷题]——贪心思想使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

此篇博客主要记录力扣中的贪心思想。

一、分配饼干

455.分发饼干    easy  2021-06-10  

假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。

对每个孩子 i,都有一个胃口值 g[i],这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j] 。如果 s[j] >= g[i],我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。

public int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);
        int i = 0; int j = 0;
        while(i < g.length && j < s.length){
            if(s[j] >= g[i]){
                j++;
                i++;
            }else{
                j++;
            }
        }
        return i;
    }

二、不重叠的区间的个数

435.无重叠区间   medium 2021-06-10

给定一个区间的集合,找到需要移除区间的最小数量,使剩余区间互不重叠。

注意:

可以认为区间的终点总是大于它的起点。
区间 [1,2] 和 [2,3] 的边界相互“接触”,但没有相互重叠。

public int eraseOverlapIntervals(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>(){
            @Override
            public int compare(int[] o1, int[] o2){
                //return o1[1] - o2[1]; 尽量不用,防止溢出
                return (o1[1] < o2[1]) ? -1 : ((o1[1] == o2[1]) ? 0 : 1);
            }
        });
        int count = 1;
        int end = intervals[0][1];
        for(int i = 1; i < intervals.length; i++){
            if(intervals[i][0] < end){
                continue;
            }else{
                end = intervals[i][1];
                count++;
            }
        }
        return intervals.length - count;
    }

三、投飞镖刺破气球

452. 用最少量的剑引爆气球   medium  2021-06-10

在二维空间中有许多球形的气球。对于每个气球,提供的输入是水平方向上,气球直径的开始和结束坐标。由于它是水平的,所以纵坐标并不重要,因此只要知道开始和结束的横坐标就足够了。开始坐标总是小于结束坐标。

一支弓箭可以沿着 x 轴从不同点完全垂直地射出。在坐标 x 处射出一支箭,若有一个气球的直径的开始和结束坐标为 xstart,xend, 且满足  xstart ≤ x ≤ xend,则该气球会被引爆。可以射出的弓箭的数量没有限制。 弓箭一旦被射出之后,可以无限地前进。我们想找到使得所有气球全部被引爆,所需的弓箭的最小数量。

给你一个数组 points ,其中 points [i] = [xstart,xend] ,返回引爆所有气球所必须射出的最小弓箭数。

         此题与上题一样,寻找不重叠区间的个数,不过是开区间与闭区间的区别。

       此题的关键在于让一个二维数组根据第二维数据进行排序,需要重写compare算法。

public int findMinArrowShots(int[][] points) {
        Arrays.sort(points, new Comparator<int[]>(){
            @Override
            public int compare(int[] o1, int[] o2){
                //return o1[1] - o1[2];
                return (o1[1] < o2[1]) ? -1 : ((o1[1] == o2[1]) ? 0 : 1);  
            }
        });
        int count = 1;
        int end = points[0][1];
        for(int i = 1;  i < points.length; i++){
            if(points[i][0] <= end){
                continue;
            }else{
                count++;
                end = points[i][1];
            }
        }
        return count;
    }

四、根据身高和顺序重组排队

406. 根据身高重建队列   medium   2021-06-11

假设有打乱顺序的一群人站成一个队列,数组 people 表示队列中一些人的属性(不一定按顺序)。每个 people[i] = [hi, ki] 表示第 i 个人的身高为 hi ,前面 正好 有 ki 个身高大于或等于 hi 的人。

请你重新构造并返回输入数组 people 所表示的队列。返回的队列应该格式化为数组 queue ,其中 queue[j] = [hj, kj] 是队列中第 j 个人的属性(queue[0] 是排在队列前面的人)。

       这个题需要先依次身高降序排列,然后将身高矮的向前移动,这样不会改变身高高的人的k值。

public int[][] reconstructQueue(int[][] people) {
        //先按照hi进行排序降序,然后移动身高较矮的向前移,这样不会影响K的值
        //按身高降序排序,同身高按k升序
        Arrays.sort(people, new Comparator<int[]>(){
            @Override
            public int compare(int[] o1, int[] o2){
                if(o1[0] - o2[0] > 0){ //降序
                    return -1; 
                }else if(o1[0] - o2[0] < 0){
                    return 1;
                }else{
                    if(o1[1] - o2[1] < 0){  //升序
                        return -1;  
                    }else if(o1[1] - o2[1] > 0){
                        return 1;
                    }else{
                        return 0;
                    }
                }
            }
        });
        for(int i = 0; i < people.length; i++){
            if(i <= people[i][1]) {
                continue;
            }else{
                int[] temp = people[i];
                int tempIndex = people[i][1];
                //for循环中需要使用tempIndex,不要使用people[i][1],因为它在变化
                for(int j = i; j > tempIndex; j--){
                    people[j] = people[j - 1];
                }
                people[tempIndex] = temp;
            }
        }
        return people;
    }

五、买卖股票的最大收益

121.买卖股票的最佳时机   easy  2021-06-11

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。

      最简单的想法当然是嵌套遍历,然后就超时了。

      记录之前最小值,然后计算今天卖出的利润, 一次遍历就够。

public int maxProfit(int[] prices) {
        int maxProfit = 0;
        int minPrice = prices[0];
        for(int i = 1; i < prices.length; i++){
            if(prices[i] <= minPrice){
                minPrice = prices[i];
            }else{
                maxProfit = Math.max(maxProfit, prices[i] - minPrice);
            }
        }
        return maxProfit;
    }

六、买卖股票的最大收益Ⅱ

122.买卖股票的最佳时机Ⅱ   easy   2021-06-11

给定一个数组 prices ,其中 prices[i] 是一支给定股票第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。

注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

        这个题我最初的思想是利用数学中类似导数的思想,找出买入时机和卖出时机。将问题复杂化了很多。事实上,只需要遍历然后累加股票在上升期的收益就行了,不需要精确地将买入卖出点定位。

public int maxProfit(int[] prices) {
        if(prices.length == 1) return 0;
        int totalProfit = 0;
        for(int i = 0; i < prices.length - 1; i++){
            if(prices[i + 1] > prices[i]){
                totalProfit += prices[i + 1] - prices[i];
            }
        }   
        return totalProfit;
    }

七、种植花朵

605. 种花问题   easy  2021-06-12

假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。

给你一个整数数组  flowerbed 表示花坛,由若干 0 和 1 组成,其中 0 表示没种植花,1 表示种植了花。另有一个数 n ,能否在不打破种植规则的情况下种入 n 朵花?能则返回 true ,不能则返回 false。

public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int len = flowerbed.length;
        if(len == 0 || (len == 1 && flowerbed[0] == 1)){
            return n == 0;
        }
        if(len == 1 && flowerbed[0] == 0){
            return n <= 1;
        }
        int insertNum = 0;
        if(flowerbed[0] == 0 && flowerbed[1] == 0){
            insertNum ++;
            flowerbed[0] = 1; 
        }
        for(int i = 0; i < len - 3; i++){
            if(flowerbed[i] == 1 && flowerbed[i + 1] == 0 && flowerbed[i + 2] == 0 && flowerbed[i + 3] == 0){
                flowerbed[i + 2] = 1;
                insertNum++;
                i++;
            }
        }
        if(flowerbed[len - 2] == 0 && flowerbed[len - 1] == 0){
            flowerbed[len - 1]= 1;
            insertNum++;
        }
        if(insertNum >= n){
            return true;
        }else{
            return false;
        }
    }

八、判断是否为子序列

392. 判断子序列   easy  2021-06-12

给定字符串 s 和 t ,判断 s 是否为 t 的子序列。

字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。

进阶:

如果有大量输入的 S,称作 S1, S2, ... , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码?

public boolean isSubsequence(String s, String t) {
        if(s.length() > t.length()) return false;
        char[] sArray = s.toCharArray();
        char[] tArray = t.toCharArray();
        int i = 0; int j = 0;
        while(i < sArray.length && j < tArray.length){
            if(tArray[j] == sArray[i]){
                i++;
                j++;
            }else{
                j++;
            }   
        }
        if(i == sArray.length){
            return true;
        }else{
            return false;
        }
    }

九、修改一个数组为非递减数组

665.非递减数组  medium  2021-06-12

给你一个长度为 n 的整数数组,请你判断在 最多 改变 1 个元素的情况下,该数组能否变成一个非递减数列。

我们是这样定义一个非递减数列的: 对于数组中任意的 i (0 <= i <= n-2),总满足 nums[i] <= nums[i + 1]。

       这道题关键在于找出局部最值,需要特别注意的是,局部最大值也伴随着局部最小值。是否将局部最大进行修改还是将最小进行修改需要进行判断。

public boolean checkPossibility(int[] nums) {
        int len = nums.length;
        if(len <= 2) return true;
        int oper = 1;
        if(nums[0] > nums[1]){
            nums[0] = nums[1];
            oper--;
        }
        if(nums[len - 1] < nums[len - 2]){
            nums[len - 1] = nums[len - 2];
            oper--;
        }
        for(int i = 1; i < len - 1; i++){
            if(nums[i] <= nums[i + 1]){
                continue;
            }
            oper--;
            if(nums[i + 1] >= nums[i - 1]){
                nums[i] = nums[i - 1];
            }else{
                nums[i + 1] = nums[i];
            }
        }
        return oper >= 0;
    }

十、子数组最大的和

53.最大子序和   easy  2021-06-12

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

public int maxSubArray(int[] nums) {
        int max = nums[0];
        for(int num : nums){
            if(max < num) max = num;
        }
        if(max <= 0){
            return max;
        }else{
            //下面的算法是针对数组中有正数的情况下的。
            int partSum = 0;
            int maxPartSum = 0;
            for(int i = 0; i < nums.length; i++){
                if(partSum + nums[i] <= 0){
                    partSum = 0;
                    continue;
                }
            partSum = partSum + nums[i];
            maxPartSum = Math.max(partSum, maxPartSum);
            }
            return maxPartSum;
        }      
    }

十一、分隔字符串使同样字符出现在一起

763. 划分字母区间   medium  2021-06-12

字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。

       

         这个题的关键在于使用一个数组记录每个字母出现的最后位置,然后比较当前小片段末尾位置与片段中出现的字母的最后位置进行对比。

public List<Integer> partitionLabels(String s) {
        int[] last = new int[26];
        for(int i = 0; i < s.length(); i++){
            last[s.charAt(i) - 'a'] = i;
        }
        List<Integer> list = new ArrayList<>();
        int start = 0; 
        int end = 0;
        for(int i = 0; i < s.length(); i++){
            end = Math.max(end, last[s.charAt(i) - 'a']);
            if(i == end){
                list.add(end - start + 1);
                start = end + 1;
            }
        }
        return list;

    }

原文地址:https://www.cnblogs.com/nobita/p/14878661.html