zoukankan      html  css  js  c++  java
  • 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].

    题目含义:如果一个数组中最大值和最小值相差为1,我们称这个数组为harmonious数组。现在给定一个数组,求出最长的harmonious数组长度。
    其实也就是求最大值和最小值之间相差1的最长子序列的长度。
     1     public int findLHS(int[] nums) {
     2         if (nums.length == 0) return 0;
     3         Map<Integer, Integer> map = new HashMap<>();
     4         for (int i = 0; i < nums.length; i++) {
     5             map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
     6         }
     7         int result = 0;
     8         for (Integer key : map.keySet()) {
     9             if (map.containsKey(key + 1)) {
    10                 result = Math.max(result, map.get(key) + map.get(key + 1));
    11             }
    12         }
    13         return result;        
    14     }
  • 相关阅读:
    DOM深度优先遍历算法
    DOM事件
    DOM修改
    DOM的方法和属性
    DOM简介
    JSON.stringify()
    JSON解析
    JSON对象
    JSON语法
    JSON对比XML
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7718989.html
Copyright © 2011-2022 走看看