leetcode 594. Longest Harmonious Subsequence

We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.

Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.

Example 1:

Input: [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].

Note: The length of the input array will not exceed 20,000.

 

本质上是一个组合问题,C(n,2),但是排序可以降低下复杂度:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
    def findLHS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # brute force
        cnt = collections.Counter(nums)
        items = cnt.items()
        items.sort(key=lambda x:x[0])
        ans = 0       
        for i in xrange(1, len(items)):
            k,v = items[i-1]:
            k2,v2 = items[i]
            if k2-k == 1:
                ans = max(ans, v2+v)
        return ans                       

还可以简化下:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
    def findLHS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # brute force
        cnt = collections.Counter(nums)
        ans = 0
        for k in cnt:
            if k+1 in cnt:
                ans = max(ans, cnt[k+1]+cnt[k])
        return ans

 此外,可以使用排序,本质上是自己build一个hash:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution(object):
    def findLHS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # brute force
        nums.sort()
        pre_k = pre_cnt = None
        ans = 0
        i = 0
        while i < len(nums):
            k = nums[i]
            cnt = 1
            while i+1<len(nums) and nums[i+1] == k:
                i += 1
                cnt += 1
            if pre_k is not None:          
                if k-pre_k==1: ans = max(pre_cnt+cnt, ans)                
            pre_k = k
            pre_cnt = cnt           
            i += 1
        return ans    
        

 

其他解法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int findLHS(vector<int>& nums) {
       sort(nums.begin(),nums.end());
       int len = 0;
       for(int i = 1, start = 0, new_start = 0; i<nums.size(); i++)
       {
 
           if (nums[i] - nums[start] > 1)   
               start = new_start;
           if (nums[i] != nums[i-1])
               new_start = i;
           if(nums[i] - nums[start] == 1)
               len = max(len, i-start+1);
       }
       return len;

 

 

另外,如果是连续的子序列,则本质上是一个计数问题:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution(object):
    def findLHS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # if sub seq is continueous
        if not nums: return 0
        min_val = max_val = nums[0]
        ans = cnt = 1
        for i in xrange(1, len(nums)):
            max_val = max(nums[i], max_val)
            min_val = min(nums[i], min_val)
            if max_val - min_val <= 1:               
                cnt += 1
                ans = max(ans, cnt)
            else:
                min_val = max_val = nums[i]
                cnt = 1
        return ans               

 

posted @   bonelee  阅读(215)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示