TypechoJoeTheme

IT技术分享

统计

[LeetCode 594] Longest Harmonious Subsequence [Java]

2017-09-17
/
0 评论
/
738 阅读
/
正在检测是否收录...
09/17

1. Description

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.

2. Runtime Distribution

3. Submission Details

4. Example

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

5. Code

public int findLHS(int[] nums) {

    if (nums == null || nums.length == 0) {
        return 0;
    }

    Map<Integer, Integer> map = new HashMap<Integer, Integer>();

    for (int i = 0; i < nums.length; i++) {
        map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
    }

    int result = 0;

    for (int key : map.keySet()) {
        if (map.containsKey(key + 1)) {
            result = Math.max(result, map.get(key + 1) + map.get(key));
        }
    }
    return result;
}

6.Test

import java.util.HashMap;
import java.util.Map;

public class LeetCode0594 {

    public int findLHS(int[] nums) {

        if (nums == null || nums.length == 0) {
            return 0;
        }

        Map<Integer, Integer> map = new HashMap<Integer, Integer>();

        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
        }

        int result = 0;

        for (int key : map.keySet()) {
            if (map.containsKey(key + 1)) {
                result = Math.max(result, map.get(key + 1) + map.get(key));
            }
        }
        return result;
    }

    public static void main(String[] args) {
        LeetCode0594 leetcode = new LeetCode0594();
        System.out.println(leetcode.findLHS(new int[] { 1, 3, 2, 2, 5, 2, 3, 7 }));
    }
}
Map
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/875/(转载时请注明本文出处及文章链接)