zoukankan      html  css  js  c++  java
  • 594. Longest Harmonious Subsequence强制差距为1的最长连续

    [抄题]:

    We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.

    Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.

    Example 1:

    Input: [1,3,2,2,5,2,3,7]
    Output: 5
    Explanation: The longest harmonious subsequence is [3,2,2,2,3].

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    [一句话思路]:

    max1 + max2 最大

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    差值必须是1 是0不行。所以[11111]输出为0。

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    熟悉hashmap的一些不常用方法,剩下就是语言表达了

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    占空间但是好用,没别的办法了那就占吧

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

    class Solution {
        public int findLHS(int[] nums) {
            //cc
            if (nums == null || nums.length == 0) {
                return 0;
            }
            
            //ini: put into hashmap
            Map<Integer,Integer> map = new HashMap<>();
            for (int num : nums) {
                map.put(num, map.getOrDefault(num, 0) + 1);
            }
            int max = 0;
            
            //for loop, getmax
            for (int key : map.keySet()) {
                if (map.containsKey(key + 1)) {
                    max = Math.max(max, map.get(key) + map.get(key + 1));
                }
            }
            
            //return max
            return max;
        }
    }
    View Code
  • 相关阅读:
    Redis常用命令手册:键值相关命令
    Redis常用命令手册:服务器相关命令
    预览图片插件
    Hibernate的generator属性之意义
    CentOS开机自动运行程序的脚本
    64位Win7安装Oracle12C临时位置权限错误解决方案
    ORACLE基本语法
    linux图形界面安装
    因xhost命令和DISPLAY环境变量操作不当导致无法启动Oracle图形化安装界面
    Linux 配置:Xmanager连接Linux图形界面
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8950203.html
Copyright © 2011-2022 走看看