class Solution { public int findLHS(int[] nums) { HashMapmap = new HashMap<>(); int temp; for(int i:nums){ temp = map.getOrDefault(i,0); map.put(i,temp+1); } temp = 0; for(Map.Entry entry : map.entrySet()){ if(map.containsKey(entry.getKey()+1)){ temp = Math.max(temp,entry.getValue()+map.get(entry.getKey()+1)); } } return temp; } }
因为数组中都是数字,哈希表是根据哈希值存储的,所以哈希表就可以实现自动排序,我们就只需要统计一遍数字,再算一下就行了。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)