贪心算法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;

   }
}
相关推荐
Emilia486.2 分钟前
【Leetcode&nowcode&数据结构】顺序表的应用
数据结构·算法·leetcode
一水鉴天7 分钟前
整体设计 逻辑系统程序 之27 拼语言整体设计 9 套程序架构优化与核心组件(CNN 改造框架 / Slave/Supervisor/ 数学工具)协同设计
人工智能·算法
小年糕是糕手16 分钟前
【数据结构】双向链表“0”基础知识讲解 + 实战演练
c语言·开发语言·数据结构·c++·学习·算法·链表
PyHaVolask1 小时前
数据结构与算法分析
数据结构·算法·图论
小王C语言1 小时前
封装红黑树实现mymap和myset
linux·服务器·算法
大佬,救命!!!1 小时前
算法实现迭代2_堆排序
数据结构·python·算法·学习笔记·堆排序
天桥下的卖艺者2 小时前
R语言手搓一个计算生存分析C指数(C-index)的函数算法
c语言·算法·r语言
Espresso Macchiato2 小时前
Leetcode 3715. Sum of Perfect Square Ancestors
算法·leetcode·职场和发展·leetcode hard·树的遍历·leetcode 3715·leetcode周赛471
草莓熊Lotso2 小时前
《C++ Stack 与 Queue 完全使用指南:基础操作 + 经典场景 + 实战习题》
开发语言·c++·算法
敲上瘾2 小时前
单序列和双序列问题——动态规划
c++·算法·动态规划