leetcode 贪心算法相关

1.1 分糖果

https://leetcode.com/problems/assign-cookies/

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

1.2 摇摆序列

https://leetcode.com/problems/wiggle-subsequence/

class Solution {
    public int wiggleMaxLength(int[] nums) {
        if(nums.length < 2){
            return nums.length;
        }
        int DOWN = -1;
        int UP = 1;
        int maxLength = 1;
        int state = 0;
        for(int i = 1;i < nums.length; i ++){
            if(i == 1 || state == 0){
                if(nums[i-1] < nums[i]){
                    state = UP;
                    maxLength ++;
                }else if(nums[i-1] > nums[i]){
                    state = DOWN;
                    maxLength ++;
                }
            }else if(state == DOWN){
                if(nums[i-1] < nums[i]){
                    state = UP;
                    maxLength ++;
                }
            }else if(state == UP){
                if(nums[i-1] > nums[i]){
                    state = DOWN;
                    maxLength ++;
                }
            }
        }
        return maxLength;
    }
}

1.3 移除K个数字

https://leetcode.com/problems/remove-k-digits/

class Solution {
    public String removeKdigits(String num, int k) {
        if(num == null || num.length() == 0){
            return "0";
        }
        
        Stack<Character> stack = new Stack<>();
        for(int i = 0;i < num.length(); i++){
            char c = num.charAt(i);
            while(!stack.isEmpty() && k > 0 && stack.peek() > c){
                stack.pop();
                k --;
            }
            if(c != '0' || !stack.isEmpty()){
              stack.push(c);    
            }
        }
        while(k > 0 && !stack.isEmpty()){
            stack.pop();
            k --;
        }
        StringBuilder sb = new StringBuilder();
        while(!stack.isEmpty()){
            sb.append(stack.pop());
        }
        sb.reverse();
        if("".equals(sb.toString())){
            return "0";
        }
        return sb.toString();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值