zoukankan      html  css  js  c++  java
  • 领扣(LeetCode)最长和谐子序列 个人题解

    和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。

    现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。

    示例 1:

    输入: [1,3,2,2,5,2,3,7]
    输出: 5
    原因: 最长的和谐数组是:[3,2,2,2,3].
    

    说明: 输入的数组长度最大不超过20,000.

    这道题问题很简单,但是一开始理解错题意,认为数组的子序列是截取数组的某一部分而不能改变其位置。

    参考相关代码后发现是任意子序列。那么使用hashmap记录出现的数和其对应出现的次数,两个大小相差1的数的长度之和 中最大的一组,就是最长的和谐子序列。

    代码如下:

     1 class Solution {
     2     public int findLHS(int[] nums) {
     3         Map<Integer, Integer> map=new HashMap<>();
     4         for (int i : nums) {
     5             if(!map.containsKey(i))
     6             {
     7                 map.put(i, 1);
     8             }
     9             else
    10             {
    11                 map.put(i, map.get(i)+1);
    12             }
    13         }
    14         int max=0;
    15         for (int i : map.keySet()) {
    16             if(map.containsKey(i+1))
    17             {
    18                 max=Integer.max(map.get(i)+map.get(i+1), max);
    19             }
    20         }
    21         return max;
    22     }
    23 }
  • 相关阅读:
    Finance_Time-Series-Analysis-with-app-in-R
    Linear_algebra_06_二次型
    Linear_algebra_05_相似对角形
    病理学
    S&p_14_参数的假设检验
    S&p_13_参数区间估计
    Finance_Analysis-of-Financial-Time-Series
    817. Linked List Components
    811. Subdomain Visit Count
    807. Max Increase to Keep City Skyline
  • 原文地址:https://www.cnblogs.com/axiangcoding/p/9911345.html
Copyright © 2011-2022 走看看