努橙刷题编

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

 https://leetcode.com/problems/longest-harmonious-subsequence

public class Solution {
    public int findLHS(int[] nums) {
        int result = 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);
        }
        for (Integer i: map.keySet()) {
            if (map.containsKey(i + 1)) {
                result = Math.max(result, map.get(i) + map.get(i + 1));
            }
        }
        return result;
    }
}

 

posted on 2017-05-25 23:24  努橙  阅读(137)  评论(0编辑  收藏  举报