zoukankan      html  css  js  c++  java
  • LeetCode.659. 分割数组为连续子序列

    # 该题的标签为 1.堆    2. 贪心算法

    目前还不知道用堆怎么解,本文只介绍贪新算法

    1. 使用贪心解法比较简单。但是看了好多解释都说得不是很明白。

    2. 本文对其进行个人的解释:

        建立两个HashMap:

         2.1  numCounts: 用来统计nums数据中出现的个数

         2.2  numNeededCounts:用来记录被需要的数的个数

         其中2.1比较好理解,我们来理解2.2,什么是被需要的数的个数?

         比如上图中,我们扫描完了1,2,3 此时我们希望下一个数,需要 4,

         那么就在numNeededCounts 中记录一下 (4,1)表示需要4 一次

    3. 看代码,里面有详细注释:

        

     1 class Solution {
     2     public boolean isPossible(int[] nums) {
     3         HashMap<Integer, Integer> numCounts = new HashMap<>();
     4         HashMap<Integer, Integer> numNeededCounts = new HashMap<>();
     5         // 统计出现的次数
     6         for (int x : nums) {
     7             numCounts.merge(x, 1, Integer::sum);
     8         }
     9         for (int x : nums) {
    10             // 一次扫描数组
    11             if (numCounts.get(x) == 0) {
    12                 continue;
    13             } else if (numNeededCounts.getOrDefault(x, 0) > 0) {
    14                 // 当前取出的数,如果在被需要的数中,则-1
    15                 numNeededCounts.merge(x, -1, Integer::sum);
    16                 // 当该数被需要了,说明该数的下一个数应该也被需要
    17                 numNeededCounts.merge(x + 1, 1, Integer::sum);
    18             } else if (numCounts.getOrDefault(x + 1, 0) > 0 && numCounts.getOrDefault(x + 2, 0) > 0) {
    19                 // 判断给定的x,在nums 中有没有x+1,x+2
    20                 // 如果有 则消耗掉 -1
    21                 numCounts.merge(x + 1, -1, Integer::sum);
    22                 numCounts.merge(x + 2, -1, Integer::sum);
    23                 // 消耗之后,记录,下一个需要的数
    24                 numNeededCounts.merge(x + 3, 1, Integer::sum);
    25             } else {
    26                 // 上面都不满足时返回 false
    27                 return false;
    28             }
    29             // 将当前数 消耗 -1
    30             numCounts.merge(x, -1, Integer::sum);
    31         }
    32         return true;
    33 
    34     }

        

  • 相关阅读:
    python自动化之利用configparser库获取配置文件中的section,option,value值
    python自动化之pymysql库连接mysql数据库封装成类
    python中封装pymysql库连接mysql数据库
    python自动化之requests库封装
    OS模块获取文件相对路径
    元素定位之xpath定位详解
    Jmeter工具-连接postgresql数据库+提取参数并应用到下个接口中
    JDK安装与环境变量配置
    python使用psycopg2连接postgresql数据库
    SQL的in的参数化查询
  • 原文地址:https://www.cnblogs.com/infoo/p/11923128.html
Copyright © 2011-2022 走看看