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

   }
}
相关推荐
凌肖战1 小时前
力扣网编程55题:跳跃游戏之逆向思维
算法·leetcode
88号技师2 小时前
2025年6月一区-田忌赛马优化算法Tianji’s horse racing optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
ゞ 正在缓冲99%…2 小时前
leetcode918.环形子数组的最大和
数据结构·算法·leetcode·动态规划
Kaltistss3 小时前
98.验证二叉搜索树
算法·leetcode·职场和发展
知己如祭3 小时前
图论基础(DFS、BFS、拓扑排序)
算法
mit6.8243 小时前
[Cyclone] 哈希算法 | SIMD优化哈希计算 | 大数运算 (Int类)
算法·哈希算法
c++bug3 小时前
动态规划VS记忆化搜索(2)
算法·动态规划
哪 吒3 小时前
2025B卷 - 华为OD机试七日集训第5期 - 按算法分类,由易到难,循序渐进,玩转OD(Python/JS/C/C++)
python·算法·华为od·华为od机试·2025b卷
军训猫猫头4 小时前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
success4 小时前
【爆刷力扣-数组】二分查找 及 衍生题型
算法