算法--贪心思想

博客围绕贪心算法展开,介绍了其在多个场景中的应用,如分配饼干、计算不重叠区间个数、投飞镖刺破气球等。通过具体题目描述,阐述了贪心策略的选择及证明其最优性,还给出了不同场景下利用贪心算法求解的思路和方法。

分配饼干

455. Assign Cookies (Easy)

Input: [1,2], [1,2,3]
Output: 2

Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2.
You have 3 cookies and their sizes are big enough to gratify all of the children,
You need to output 2.

题目描述:每个孩子都有一个满足度,每个饼干都有一个大小,只有饼干的大小大于等于一个孩子的满足度,该孩子才会获得满足。求解最多可以获得满足的孩子数量。

给一个孩子的饼干应当尽量小又能满足该孩子,这样大饼干就能拿来给满足度比较大的孩子。因为最小的孩子最容易得到满足,所以先满足最小的孩子。

证明:假设在某次选择中,贪心策略选择给当前满足度最小的孩子分配第 m 个饼干,第 m 个饼干为可以满足该孩子的最小饼干。假设存在一种最优策略,给该孩子分配第 n 个饼干,并且 m < n。我们可以发现,经过这一轮分配,贪心策略分配后剩下的饼干一定有一个比最优策略来得大。因此在后续的分配中,贪心策略一定能满足更多的孩子。也就是说不存在比贪心策略更优的策略,即贪心策略就是最优策略。

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

不重叠的区间个数

435. Non-overlapping Intervals (Medium)

Input: [ [1,2], [1,2], [1,2] ]

Output: 2

Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Input: [ [1,2], [2,3] ]

Output: 0

Explanation: You don't need to remove any of the intervals since they're already non-overlapping.

题目描述:计算让一组区间不重叠所需要移除的区间个数。

先计算最多能组成的不重叠区间个数,然后用区间总个数减去不重叠区间的个数。

在每次选择中,区间的结尾最为重要,选择的区间结尾越小,留给后面的区间的空间越大,那么后面能够选择的区间个数也就越大。

按区间的结尾进行排序,每次选择结尾最小,并且和前一个区间不重叠的区间。

class Solution {
    public int eraseOverlapIntervals(int[][] intervals) {
        if(intervals.length<1){
            return 0;
        }
        Arrays.sort(intervals, new Comparator<int[]>(){
           public int compare(int[] s1, int[] s2){
               return s1[1]-s2[1];
           } 
        });
        int count = 1;
        int end = intervals[0][1];
        for(int i=0;i<intervals.length;i++){
            if(intervals[i][0]<end){
                continue;
            }
            end = intervals[i][1];
            count++;
        }
        return intervals.length-count;
    }
}

投飞镖刺破气球

452. Minimum Number of Arrows to Burst Balloons (Medium)

Input:
[[10,16], [2,8], [1,6], [7,12]]

Output:
2

题目描述:气球在一个水平数轴上摆放,可以重叠,飞镖垂直投向坐标轴,使得路径上的气球都被刺破。求解最小的投飞镖次数使所有气球都被刺破。

也是计算不重叠的区间个数,不过和 Non-overlapping Intervals 的区别在于,[1, 2] 和 [2, 3] 在本题中算是重叠区间。

class Solution {
    public int findMinArrowShots(int[][] points) {
        if(points.length<1){
            return 0;
        }
        Arrays.sort(points, new Comparator<int[]>(){
            public int compare(int[] a1, int[] a2){
                return a1[1] - a2[1];
            }
        });
        int end = points[0][1];
        int count = 1;
        for(int i = 0;i<points.length;i++){
            if(points[i][0]<=end){
                continue;
            }
            count++;
            end = points[i][1];
        }
        return count;
    }
}

根据身高和序号重组队列

406. Queue Reconstruction by Height(Medium)

Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

题目描述:一个学生用两个分量 (h, k) 描述,h 表示身高,k 表示排在前面的有 k 个学生的身高比他高或者和他一样高。

为了使插入操作不影响后续的操作,身高较高的学生应该先做插入操作,否则身高较小的学生原先正确插入的第 k 个位置可能会变成第 k+1 个位置。

身高 h 降序、个数 k 值升序,然后将某个学生插入队列的第 k 个位置中。

class Solution {
    public int[][] reconstructQueue(int[][] people) {
        if(people.length==0){
            return new int[0][0];
        }
        //按身高降序,按k升序将数组重排
        Arrays.sort(people, new Comparator<int[]>(){
            public int compare(int[] a1, int[] a2){
                return a1[0]==a2[0]?a1[1]-a2[1]:a2[0]-a1[0];
            }
        });
        List<int[]> list= new ArrayList();
        for(int[] a: people){
            //以数据对应的k将数组中元素一次插入list
            list.add(a[1],a);
        }
        return list.toArray(new int[list.size()][]);
    }
}

买卖股票最大的收益

121. Best Time to Buy and Sell Stock (Easy)

题目描述:一次股票交易包含买入和卖出,只进行一次交易,求最大收益。

只要记录前面的最小价格,将这个最小价格作为买入价格,然后将当前的价格作为售出价格,查看当前收益是不是最大收益。

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

 买卖股票的最大收益 II

122. Best Time to Buy and Sell Stock II (Easy)

题目描述:可以进行多次交易,多次交易之间不能交叉进行,可以进行多次交易。

对于 [a, b, c, d],如果有 a <= b <= c <= d ,那么最大收益为 d - a。而 d - a = (d - c) + (c - b) + (b - a) ,因此当访问到一个 prices[i] 且 prices[i] - prices[i-1] > 0,那么就把 prices[i] - prices[i-1] 添加到收益中。

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

种植花朵

605. Can Place Flowers (Easy)

Input: flowerbed = [1,0,0,0,1], n = 1
Output: True

题目描述:flowerbed 数组中 1 表示已经种下了花朵。花朵之间至少需要一个单位的间隔,求解是否能种下 n 朵花。

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int i = 0;
        int count = n;
        while(i<flowerbed.length && count!=0){
            //当前i为0,且i前一个为0,i后一个为0时判断可以种花,i+=2
            //判断两个边界:
            //i==0时,左边可以不为0;
            //i==flowebed.length-1时,右边可以不为0;
            if(flowerbed[i]==0 && (i == 0 || flowerbed[i - 1] == 0)
                && (i == flowerbed.length-1 || flowerbed[i + 1] == 0)){
                count--;
                i+=2;
            }else
                i++;
        }
        return count==0;
    }
}

判断是否为子序列

392. Is Subsequence (Medium)

s = "abc", t = "ahbgdc"
Return true.
//38ms
class Solution {
    public boolean isSubsequence(String s, String t) {
        int si = 0;
        int ti = 0;
        while(si<s.length() && ti<t.length()){
            if(s.charAt(si) == t.charAt(ti)){
                si++;
            }
            ti++;
        }
        return si==s.length();
    }
}
//1 ms
class Solution {
    public boolean isSubsequence(String s, String t) {
        int index = -1;
        for (char c : s.toCharArray()) {
            //从t字符串的index+1位置往后能否找到c字符
            index = t.indexOf(c, index + 1);
            //不能,直接返回false
            if (index == -1) {
                return false;
            }
        }
        return true;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值