其他分享
首页 > 其他分享> > leetcode 845

leetcode 845

作者:互联网

山峰数组指, 先严格递增, 再严格递减的数组. 现给到一个数组, 找到一个连续子数组, 使得该子数组是山峰数组, 输出最长的该子数组的长度.

要求只遍历一遍数组, 并且空间复杂度为O(1)

想了10分钟知道怎么写, 写了40分钟才debug没问题, 提交了5次前后, 我觉得我是一个sb.

class Solution:
    def longestMountain(self, arr: List[int]) -> int:
        result = 0
        if len(arr) <= 2:
            return 0
        result = 0
        first_index = 0
        pre_num = arr[0]
        left = 0
        sign = 0
        for i in range(1, len(arr)):
            # print(f"current index: {i}, sign = {sign}, left = {left}")
            current_num = arr[i]
            if pre_num < current_num:
                if sign == 0:
                    pass
                else:
                    tmp = i - 1 - left + 1
                    result = max(tmp, result)
                    
                    left = i - 1
                    sign = 0
            elif pre_num == current_num:
                if sign == 0:
                    left = i
                else:
                    
                    tmp = i - 1 - left + 1
                    result = max(tmp, result)
                    # print(left, i, tmp)
                    
                    left = i
                    sign = 0
            else:
                if sign == 0:
                    if left == i - 1:
                        left = i
                    else:
                        sign = 1
                        
                        tmp = i - left + 1
                        result = max(tmp, result)
                        # print(left, i, tmp)
                else:
                    tmp = i - left + 1
                    result = max(tmp, result)
                    # print(left, i, tmp)

            pre_num = current_num
        return result

标签:山峰,845,int,arr,该子,数组,分钟,leetcode
来源: https://www.cnblogs.com/mangmangbiluo/p/15586720.html