zoukankan      html  css  js  c++  java
  • 0594. Longest Harmonious Subsequence (E)

    Longest Harmonious Subsequence (E)

    题目

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

    Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.

    A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.

    Example 1:

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

    Example 2:

    Input: nums = [1,2,3,4]
    Output: 2
    

    Example 3:

    Input: nums = [1,1,1,1]
    Output: 0
    

    Constraints:

    • 1 <= nums.length <= 2 * 10^4
    • -10^9 <= nums[i] <= 10^9

    题意

    在给定数组中找到一个子数组,使其中的最大值和最小值的差正好为1。

    思路

    根据题意,这样的子数组中只可能存在两种不同的数,有以下两种方法:

    先将数组排序,再利用滑动窗口找到首尾差为1的子数组,复杂度为(O(N))

    或可以用HashMap记录每个数字的出现次数,在遍历时,当前数为num,判断num-1和num+1是否存在,存在的话则比较max(ans, num出现次数 + (num-1) or (num+1)出现次数)。


    代码实现

    Java

    排序

    class Solution {
        public int findLHS(int[] nums) {
            if (nums.length == 1) {
                return 0;
            }
    
            int ans = 0;
            int left = 0, right = 1;
    
            Arrays.sort(nums);
            while (left <= nums.length - 2) {
                if (nums[right] - nums[left] == 1) {
                    ans = Math.max(ans, right - left + 1);
                    right++;
                } else if (nums[right] - nums[left] > 1) {
                    left++;
                } else {
                    right++;
                }
                if (left == right) right++;
                if (right == nums.length) break;
            }
    
            return ans;
        }
    }
    

    Hash

    class Solution {
        public int findLHS(int[] nums) {
            int ans = 0;
            Map<Integer, Integer> map = new HashMap<>();
            for (int num : nums) {
                int cnt = map.getOrDefault(num, 0) + 1;
                if (map.containsKey(num - 1)) {
                    ans = Math.max(ans, map.get(num - 1) + cnt);
                }
                if (map.containsKey(num + 1)) {
                    ans = Math.max(ans, map.get(num + 1) + cnt);
                }
                map.put(num, cnt);
            }
            return ans;
        }
    }
    
  • 相关阅读:
    mySQL 重点
    JS代码预解析原理、函数相关、面向对象
    PHP中对数组进行操作的常用函数总结
    js函数和数组总结
    深入理解css网页布局细节
    AngularJS表单验证
    发送消息 缺少 更新的字段值
    springboot 下 logback + MDC的使用
    Mock的使用2
    StringUtils # split 的坑
  • 原文地址:https://www.cnblogs.com/mapoos/p/14374447.html
Copyright © 2011-2022 走看看