思路: 就是利用HashMap的containsKey()函数;遍历HashMap,遍历过程中,比较出最大 (max , 当前的value + key加减1的value )
class Solution {
public int findLHS(int[] nums) {
Map<Integer ,Integer> map = new HashMap<>();
for(int num : nums)
{
if(map.containsKey(num))
{map.put(num, map.get(num) + 1);}
else
{map.put(num, 1);}
}
int max = 0;
for(Map.Entry<Integer, Integer> entry : map.entrySet())
{
if(map.containsKey(entry.getKey() - 1))
max = Math.max(max , entry.getValue() + map.get(entry.getKey() - 1));
if(map.containsKey(entry.getKey() + 1))
max = Math.max(max , entry.getValue() + map.get(entry.getKey() + 1));
}
return max;
}
}