Question
594. Longest Harmonious Subsequence
Solution
题目大意:找一个最长子序列,要求子序列中最大值和最小值的差是1。
思路:构造一个map,保存每个元素出现的个数,再遍历这个map,算出每个元素与其邻元素出现的次数和,并找到最大的那个数
Java实现:
public int findLHS(int[] nums) {
if (nums == null || nums.length == 0) return 0;
Map<Integer, Integer> map = new HashMap<>();
for (int tmp : nums) {
Integer cnt = map.get(tmp);
if (cnt == null) cnt = 0;
map.put(tmp, cnt + 1);
}
int count = 0;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
int before = map.get(entry.getKey() - 1) != null ? map.get(entry.getKey() - 1) : -entry.getValue();
int next = map.get(entry.getKey() + 1) != null ? map.get(entry.getKey() + 1) : -entry.getValue();
if (before + entry.getValue() > count) count = before + entry.getValue();
if (next + entry.getValue() > count) count = next + entry.getValue();
}
return count;
}