1. 程式人生 > >leetcode 376 擺動序列

leetcode 376 擺動序列

 def wiggleMaxLength(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        diff=[]
        for i in range(1,len(nums)):
            if nums[i]-nums[i-1]>0:
                diff.append(1)
            elif nums[i]-nums[i-1]<0:
                diff.append(2)
        if not diff:
            return 1 #處理相等的數的情況
        ans=1
        for i in range(1,len(diff)):
            if diff[i]!=diff[i-1]:
                ans+=1
        return ans+1

  

 

    def wiggleMaxLength(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        diffs=[a-b for a,b in zip([float('nan')]+nums,nums+[float('nan')]) if a-b]
        return sum(not a*b>0 for a,b in zip(diffs,diffs[1:])) #not是為了排除nan的情況

  

方法二:

    def wiggleMaxLength(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # dp solution
        if not nums:
            return 0
        down,up=1,1
        for i in range(1,len(nums)):
            if nums[i]>nums[i-1]:
                up=down+1
            elif nums[i]<nums[i-1]:
                down=up+1
        return max(down,up)