zoukankan      html  css  js  c++  java
  • LeetCode 594. Longest Harmonious Subsequence (最长的协调子序列)

    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].
    

    Note: The length of the input array will not exceed 20,000.


    题目标签:HashMap

      这道题给我们一个数字array, 让我们找出最长协调的子序列的长度。

      首先把每一个数字 和它出现次数 存入 map。

      然后遍历map 的 keySet,对于每一个key,检查 key + 1 是否也存在,存在的话,就把 key 和 key + 1 的value 相加,保留一个最大的 max 就是最长的长度。  

    Java Solution:

    Runtime beats 69.23% 

    完成日期:06/07/2017

    关键词:HashMap

    关键点:遍历key,把key 和 key + 1 的value 相加

     1 class Solution 
     2 {
     3     public int findLHS(int[] nums) 
     4     {
     5         HashMap<Integer, Integer> map = new HashMap<>();
     6         int res = 0;
     7         
     8         
     9         for(int num: nums)
    10             map.put(num, map.getOrDefault(num, 0) + 1);
    11         
    12         // for each key, check its key + 1
    13         for(int key: map.keySet())
    14         {
    15             if(map.containsKey(key + 1))
    16                 res = Math.max(res, map.get(key) + map.get(key + 1));
    17             
    18         }
    19         
    20        
    21         return res;
    22     }
    23 }

    参考资料:N/A

    LeetCode 算法题目列表 - LeetCode Algorithms Questions List

  • 相关阅读:
    [GO]使用map生成 json
    [GO]通过结构体生成json
    [GO]正则表达式
    [GO]字符串的使用
    [GO]revoer的应用
    [GO]panic的应用
    微信公众平台自定义菜单及高级接口PHP SDK
    论MySQL何时使用索引,何时不使用索引
    MYSQL explain详解
    Mysql两种存储引擎的优缺点
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7087985.html
Copyright © 2011-2022 走看看