问题:
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].
Note: The length of the input array will not exceed 20,000.
解决:
①采用hash map记录数值及其个数,找到差值为1的计算总个数,取最大的即可。耗时73ms。
public class Solution {
public int findLHS(int[] nums) {
Map<Integer,Integer> map = new HashMap<>();
for (int n : nums) {
map.put(n,map.getOrDefault(n,0) + 1);
}
int max = 0;
int sum = 0;
for (Map.Entry<Integer,Integer> entry : map.entrySet()) {
if(map.containsKey(entry.getKey() + 1)){
sum = entry.getValue() + map.get(entry.getKey() + 1);
if (max < sum) {
max = sum;
}
}
}
return max;
}
}
②先对数组进行排序,使用四个指针从头到尾扫描,耗时41ms.
public class Solution {
public static int findLHS(int[] nums) {
int max = 0;
Arrays.sort(nums);
int curi = 0;//指向第一个数的第一个下标
int curj = 0;//指向第一个数的最后一个下标
while(curj + 1 < nums.length && nums[curj + 1] == nums[0]) curj ++;//curj初始化
for (int nexti = curj + 1;nexti < nums.length ;nexti ++ ) {//nexti指向第二个数的第一个下标
int nextj = nexti;//nextj指向第二个数的最后一个下标
while(nextj + 1 < nums.length && nums[nextj + 1] == nums[nexti]) nextj ++;
if (nums[curi] + 1 == nums[nexti]) {
max = Math.max(max,nextj - curi + 1);
}
curi = nexti;
curj = nextj;
nexti = curj;
}
return max;
}
}