forked from yehongzhi/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
[594]最长和谐子序列.java
32 lines (32 loc) · 1.01 KB
/
[594]最长和谐子序列.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public int findLHS(int[] nums) {
Map<Integer, Integer> map = new LinkedHashMap<>();
Arrays.sort(nums);
for (int num : nums) {
Integer count = map.get(num);
if (count == null) {
map.put(num, 1);
} else {
count++;
map.put(num, count);
}
}
int maxLength = 0;
int preNum = Integer.MAX_VALUE;
int preCount = 0;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (preNum == Integer.MAX_VALUE) {
preNum = entry.getKey();
preCount = entry.getValue();
} else {
Integer currNum = entry.getKey();
if ((currNum - preNum) == 1) {
maxLength = Math.max(entry.getValue() + preCount, maxLength);
}
preNum = currNum;
preCount = entry.getValue();
}
}
return maxLength;
}
}