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

   }
}
相关推荐
2401_877274242 分钟前
2025数据结构实验八:排序
数据结构·算法·排序算法
J2虾虾6 分钟前
空间矢量数据结构及其表达
算法
Neil今天也要学习17 分钟前
永磁同步电机无速度算法--永磁同步电机转子位置精确估计的误差抑制方法
算法
Irene199119 分钟前
JavaScript 常见算法复杂度总结(大O表示法)
javascript·算法
开心比对错重要26 分钟前
进程、线程、虚拟线程详解及线程个数设置
java·jvm·算法·面试
爱学大树锯37 分钟前
【594 · 字符串查找 II】
java·开发语言·算法
m0_692457101 小时前
图像噪点消除
人工智能·算法
2401_841495641 小时前
【Python高级编程】图着色动态可视化 APP
python·算法·matplotlib·tkinter·回溯法·图着色算法·动态可视化工具
youngee111 小时前
hot100-53搜索旋转排序数组
数据结构·算法·leetcode
烟雨梵兮1 小时前
-刷题小结19
算法