首页 > 其他分享 >leetcode 594. Longest Harmonious Subsequence

leetcode 594. Longest Harmonious Subsequence

时间:2023-05-30 17:33:34浏览次数:51  
标签:cnt val nums int max Subsequence Harmonious Longest ans

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),但是排序可以降低下复杂度:

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

还可以简化下:

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:

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

 

其他解法:

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;

 

 

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

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

 

标签:cnt,val,nums,int,max,Subsequence,Harmonious,Longest,ans
From: https://blog.51cto.com/u_11908275/6381017

相关文章

  • upc 6597: Don't Be a Subsequence (字符串的最短不匹配子序列 dp)
    6597:Don'tBeaSubsequence时间限制:1Sec  内存限制:128MB提交:237  解决:45[提交][状态][讨论版][命题人:admin] 题目描述AsubsequenceofastringSisastringthatcanbeobtainedbydeletingzeroormorecharactersfromSwithoutchangingtheor......
  • 128. Longest Consecutive Sequence刷题笔记
    取巧用了python自带的排序算法,该算法为Timsort,复杂度为nlog(n)classSolution:deflongestConsecutive(self,nums:List[int])->int:ifnotnums:return0nums.sort()res=0length=1foriinrange(len(nu......
  • 32. Longest Valid Parentheses刷题笔记
    用stack和dp来做classSolution:deflongestValidParentheses(self,s:str)->int:dp,stack=[0]*(len(s)+1),[]foriinrange(len(s)):ifs[i]=='(':stack.append(i)else:......
  • 1332. Remove Palindromic Subsequences刷题笔记
    容易陷入思维盲区,只有a和b的字符串,只会有2个或1个回文classSolution:defremovePalindromeSub(self,s:str)->int:return2-(s==s[::-1])......
  • abc271_e Subsequence Path 题解
    SubsequencePath题意有\(n\)个城市和\(m\)条有向道路,编号从\(1\)开始,第\(i\)条道路从\(a_i\)到\(b_i\),长度为\(c_i\)。给定一个长度为\(k\)的序列\(e\),我们定义从\(1\)到\(n\)的一条路径是优秀的当且仅当:经过的边的编号按顺序构成\(e\)的一个子序列。......
  • subsequence1 (牛客多校) (2个串比大小, DP, 组合数)
    题面大意:给定2个字符串,问有多少个子字符串S,是大于t的 思路数据范围很小,因此考虑n^2做法分2步,位数s>位数t的时候然后位数相等的时候利用DP,处理,分别就是枚举前k个数和s相同,然后k+1个数比t大就可以. 具体思路自己想想,和那个比较像   cons......
  • CF1794C Scoring Subsequences题解
    文中\(a\)为题目中给的\(a\)。如果我们要求\(a_1,a_2,a_3,\dots,a_m\)的结果,那么我们可以把\(a\)数组从后往前依次除以\(i\),\(i\)从\(1\)到\(n\),即为\(\frac{a_1}{m},\frac{a_2}{m-1},\frac{a_3}{m-2},\dots,\frac{a_{m-1}}{2},\frac{a_m}{1}\),并将其保......
  • 「USACO2016JAN」Subsequences Summing to Sevens
    [USACO16JAN]SubsequencesSummingtoSevensS题目描述FarmerJohn's\(N\)cowsarestandinginarow,astheyhaveatendencytodofromtimetotime.EachcowislabeledwithadistinctintegerIDnumbersoFJcantellthemapart.FJwouldliketota......
  • CF750E - New Year and Old Subsequence
    题意:给一个字符串,每次询问它的一个区间,问最少删除多少个字符,使得区间没有子序列2016,但是有子序列2017。Mysolution首先考虑贪心,通过预处理的方式找到区间最后一个7,依次往前贪心的找到最靠后的一组2017。接下来,我们需要7的后面没有6,7前面的部分不能组合出2016。我们先......
  • PAT Advanced 1007. Maximum Subsequence Sum
    PATAdvanced1007.MaximumSubsequenceSum1.ProblemDescription:Givenasequenceof\(K\)integers{\(N_1,N_2,...,N_K\)}.Acontinuoussubsequenceisdefinedtobe{\(N_i,N_{i+1},...,N_j\)}where\(1≤i≤j≤K\).TheMaximumSubsequencei......