本題題意:
在一個數組中,找一個這樣的和諧數組,他們的最大值和最小值的差值正好是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;