|
45 | 45 | <li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
|
46 | 46 | </ul>
|
47 | 47 |
|
48 |
| - |
49 | 48 | ## 解法
|
50 | 49 |
|
51 | 50 | <!-- 这里可写通用的实现逻辑 -->
|
52 | 51 |
|
| 52 | +先用哈希表统计每个元素出现的次数。然后遍历数组,判断比每个元素 `num` 大 1 的数字 `num + 1` 是否在哈希表中,若是,累计 `num` 和 `num + 1` 出现的次数,与最大值 res 比较。若更大,则替换。最后返回 res 即可。 |
| 53 | + |
53 | 54 | <!-- tabs:start -->
|
54 | 55 |
|
55 | 56 | ### **Python3**
|
56 | 57 |
|
57 | 58 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
58 | 59 |
|
59 | 60 | ```python
|
60 |
| - |
| 61 | +class Solution: |
| 62 | + def findLHS(self, nums: List[int]) -> int: |
| 63 | + counter = collections.Counter(nums) |
| 64 | + res = 0 |
| 65 | + for num in nums: |
| 66 | + if num + 1 in counter: |
| 67 | + res = max(res, counter[num] + counter[num + 1]) |
| 68 | + return res |
61 | 69 | ```
|
62 | 70 |
|
63 | 71 | ### **Java**
|
64 | 72 |
|
65 | 73 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
66 | 74 |
|
67 | 75 | ```java
|
| 76 | +class Solution { |
| 77 | + public int findLHS(int[] nums) { |
| 78 | + Map<Integer, Integer> counter = new HashMap<>(); |
| 79 | + for (int num : nums) { |
| 80 | + counter.put(num, counter.getOrDefault(num, 0) + 1); |
| 81 | + } |
| 82 | + int res = 0; |
| 83 | + for (int num : nums) { |
| 84 | + if (counter.containsKey(num + 1)) { |
| 85 | + res = Math.max(res, counter.get(num) + counter.get(num + 1)); |
| 86 | + } |
| 87 | + } |
| 88 | + return res; |
| 89 | + } |
| 90 | +} |
| 91 | +``` |
| 92 | + |
| 93 | +### **C++** |
| 94 | + |
| 95 | +```cpp |
| 96 | +class Solution { |
| 97 | +public: |
| 98 | + int findLHS(vector<int>& nums) { |
| 99 | + unordered_map<int, int> counter; |
| 100 | + for (int num : nums) { |
| 101 | + ++counter[num]; |
| 102 | + } |
| 103 | + int res = 0; |
| 104 | + for (int num : nums) { |
| 105 | + if (counter.count(num + 1)) { |
| 106 | + res = max(res, counter[num] + counter[num + 1]); |
| 107 | + } |
| 108 | + } |
| 109 | + return res; |
| 110 | + } |
| 111 | +}; |
| 112 | +``` |
68 | 113 |
|
| 114 | +### **Go** |
| 115 | +
|
| 116 | +```go |
| 117 | +func findLHS(nums []int) int { |
| 118 | + counter := make(map[int]int) |
| 119 | + for _, num := range nums { |
| 120 | + counter[num]++ |
| 121 | + } |
| 122 | + res := 0 |
| 123 | + for _, num := range nums { |
| 124 | + if counter[num+1] > 0 { |
| 125 | + res = max(res, counter[num]+counter[num+1]) |
| 126 | + } |
| 127 | + } |
| 128 | + return res |
| 129 | +} |
| 130 | +
|
| 131 | +func max(a, b int) int { |
| 132 | + if a > b { |
| 133 | + return a |
| 134 | + } |
| 135 | + return b |
| 136 | +} |
69 | 137 | ```
|
70 | 138 |
|
71 | 139 | ### **...**
|
|
0 commit comments