这个不一定要,把map里的数据排序,个人是想练习重写集合比较器,所以把map里数据按自己相要的规则排序了
和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。
现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。
示例 1:
输入: [1,3,2,2,5,2,3,7] 输出: 5 原因: 最长的和谐数组是:[3,2,2,2,3].
说明: 输入的数组长度最大不超过20,000.
class Solution {
public int findLHS(int[] nums) {
if(nums.length==0)
return 0;
int length=0;
HashMap<Integer,Integer>map=new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++)
{
if(map.containsKey(nums[i]))
map.put(nums[i],map.get(nums[i])+1);
else
map.put(nums[i],1);
}
Set<Map.Entry<Integer,Integer>> set=map.entrySet();
ArrayList<Map.Entry<Integer,Integer>>list=new ArrayList<>(set);
Collections.sort(list,new Comparator<Map.Entry<Integer,Integer>>(){
@Override
public int compare(Map.Entry<Integer,Integer>o1,Map.Entry<Integer,Integer>o2)
{
return o1.getKey().compareTo(o2.getKey());
}
});
for(int i=1;i<list.size();i++)
{
int count=0;
if(Math.abs(list.get(i).getKey()-list.get(i-1).getKey())==1)
count+=list.get(i-1).getValue()+list.get(i).getValue();
length=length>count?length:count;
}
return length;
}
}