We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.
Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.
Example 1:
Input: [1,3,2,2,5,2,3,7] Output: 5 Explanation: The longest harmonious subsequence is [3,2,2,2,3].------------------------------------------------------------------------------------------------------------------------------------------------------------------------
题意
从一个数组中找到一个harmonious array,这个harmonious array定义为数组的最大值和最小值之差等于1,现在需要找到最长的这种数组。
思路
找到最长的就是要找到出现次数最多的,然后可以利用hashmap来统计某个数字的出现次数,然后再循环数组,找每个数字n的次数,以及每个数字加1(n+1)后的数字出现次数,
然后比较结果,找到最大的即可。不需要找n-1的出现次数。
代码
public static int findLHS(int[] nums){
Map<Long, Integer> map = new HashMap<>();
for (long num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
int result = 0;
for (long key : map.keySet()) {
if (map.containsKey(key + 1)) {
result = Math.max(result, map.get(key + 1) + map.get(key));
}
}
return result;
}
这里有用到map.getOrDefault(args,default)方法,这个方法的作用是在map中找key等于args,如果找到返回value,如果没找到则返回默认值default。
相似的方法putIfAbsent方法,这个方法也是在map中根据key找,如果找到,返回value,如果没找到,插入这个key,返回null;
putIfAbsent
If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
getOrDefault
Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
If your goal is only to retrieve the value, then use getOrDefault
. Else, if you want to set the value when it does not exist, use putIfAbsent
.
我写的另外一个方法
public static int findLHS(int[] nums) {
int length = nums.length;
if(nums == null || nums.length <=0)
return 0;
int firstValue = nums[0];
int i=1;
int maxCount=0;
while(i<length){
int count=0;
int j=0;
boolean flag = false;
while(j<length){
if( nums[j] == firstValue+1){
flag = true;
count++;
}
if(nums[j] == firstValue){
count++;
}
j++;
}
firstValue = nums[i];
if(count > maxCount && flag){
maxCount = count;
}
i++;
}
return maxCount;
}
运行了几个测试用例,返回值都是对的,但是leetCode提示超时