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; } }
时间: 2024-09-28 22:45:44