本题题意:
在一个数组中,找一个这样的和谐数组,他们的最大值和最小值的差值正好是1.
Input: [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].java
就是能够仍是不连续的。python
第一遍写:数组
Map<Integer, Integer> dc = new HashMap<>(); int res = 0; for (int i = 0; i < nums.length; ++i){ if (dc.containsKey(nums[i]) ) continue; else{ int tr = 1; boolean h = false; for (int j = i + 1; j < nums.length; ++j) if (nums[j] == nums[i]) tr += 1; else if(nums[j] == nums[i] + 1){ tr += 1; h = true; } res = Math.max(res, h ? tr: 0); tr = 1; h = false; for(int j = i + 1; j < nums.length; ++j) if (nums[j] == nums[i]) tr += 1; else if(nums[j] == nums[i] - 1){ tr += 1; h = true; } res = Math.max(res, h ? tr : 0); } } return res;
上面的思路是:用Hash记录,nums[i]的最大harmonious序列长度
下面修改hash,让他直接记录次数不是更好嘛,而后再算。
第二遍写:code
Map<Integer, Integer> dc = new HashMap<>(); for (int i = 0; i < nums.length; ++i) if (dc.containsKey(nums[i])) dc.put(nums[i], dc.get(nums[i]) + 1); else dc.put(nums[i], 1); int res = 0; for (int i = 0; i < nums.length; ++i){ if (dc.containsKey(nums[i] - 1)) res = Math.max(res, dc.get(nums[i] - 1) + dc.get(nums[i])); if (dc.containsKey(nums[i] + 1)) res = Math.max(res, dc.get(nums[i] + 1) + dc.get(nums[i])); } return res;
而后又用python写了一遍.get
def findLHS(self, nums: List[int]) -> int: dc = collections.Counter(nums) #nums[i] : counts res = 0 for key, c in dc.items(): if dc[key - 1] != 0: res = max(res, dc[key] + dc[key - 1]) if dc[key + 1] != 0: res = max(res, dc[key] + dc[key + 1]) return res
最后嘞,看答案感受又菜鸡了,实际上是不用断定key - 1的,为何嘞?hash
dc.put(num, dc.getOrDefault(num, 0) + 1);
代码以下:it
Map<Integer, Integer> dc = new HashMap<>(); int res = 0; for (int num : nums) dc.put(num, dc.getOrDefault(num, 0) + 1); for (int num : nums) if (dc.containsKey(num + 1)) res = Math.max(res, dc.get(num + 1) + dc.get(num)); return res;