贪心算法day(1)

1.将数组和减半的最少操作次数

链接:. - 力扣(LeetCode)

思路:创建大跟堆将最大的数进行减半

注意点:double t = queue.poll()会将queue队列数字减少一个后再除以2,queue.offer(queue.poll()/ 2)

复制代码
class Solution {
     public int halveArray(int[] nums) {
        //如何建立大根堆??
        PriorityQueue<Double> queue = new PriorityQueue<>((a,b)->b.compareTo(a));
      double sum = 0.0;
        int count = 0;
       for(int x:nums){
           queue.offer((double) x);
           sum+=x;
       }
      sum /= 2.0;

        while(sum > 0){
            
         double t = queue.poll() / 2.0;
            sum -= t;
            count++;
            queue.offer(t);
        }
        return count;

    }
}

2.最大数

链接:. - 力扣(LeetCode)

主要问题:如何将数字改为字符串以及排序

复制代码
class Solution {
    public static String largestNumber(int[] nums) {
        //把数字转化成字符串 把两个字符串拼接在一起比较字符串的字典序
        //ab > ba a在前b在后 ab < ba b在前a在后

        //转化字符串
        int n = nums.length;
        String[] str = new String[n];
        for (int i = 0; i < n; i++) {
            str[i] = ""+nums[i];
        }
        //排序
        Arrays.sort(str,(a,b)->{
            return (b+a).compareTo(a+b);
        });
       //提取结果
        StringBuffer ret = new StringBuffer();
       for(String x: str){
           ret.append(x);
       }
       if(ret.charAt(0) == '0'){
           return "0";
       }
       return ret.toString();
    }
}

3.摆动序列

链接:. - 力扣(LeetCode)

思路:把数子画成波峰波谷 左右端点以及波峰波谷就是我们要找的最大摆序列

问题:如何表示波峰波谷以及什么情况下添加最大摆动序列

复制代码
class Solution {
   public int wiggleMaxLength(int[] nums) {
        int n = nums.length;
         if(n < 2){
             return n;
         }
         int left = 0;
         int count = 0;
        for (int i = 0; i < n - 1; i++) {
            int right = nums[i+1] - nums[i];
            if(right == 0) continue;
            if(left * right <= 0){
                count++;
            }
            left = right;
        }
        return count + 1;

   }
}
相关推荐
BothSavage8 小时前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn8 小时前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
烬羽10 小时前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
先吃饱再说1 天前
判断回文字符串,从一行代码到双指针优化
算法
黄敬峰1 天前
深入理解算法核心:从递归思想、数组扁平化到快速排序
算法
得物技术1 天前
从狂野代码到按目标生产:得物推荐 AI Harness 的工程化实践|AICon 演讲整理
人工智能·算法·架构
AI小老六1 天前
SkillOpt 架构拆解:把 Skill 文本当参数,用执行轨迹训练 Agent
后端·算法·ai编程
胡萝卜术1 天前
从“分数打架”到“排名投票”:为什么你的ChatBI必须用RRF?
算法·设计模式·面试
Asize1 天前
初识DFS 与 BFS:递归、队列与图遍历
算法