提取数组中的 upward/downwards 个趋势

Extracting upward/downwards trends in an array

我有一个由不同日期的温度组成的数组。我的目标是提取温度在 n 天内升高或降低的元素。

假设我们有一个包含以下温度的数组

temp=[4,5,7,8,9,7,6,7,8,6,5,4,3,2]

如果我们说 n=3,那么如果温度连续两天上升但在第三天下降,我们不想提取该信息,只考虑温度所在的元素havs increased/decreased 至少连续 n 天。

假设 n=3,那么从上面的临时数组中,提取将是

increasingTemp1=[4,5,7,8,9] ( i.e temp[0:5] )
increasingTemp2=[6,7,8]     ( i.e temp[6:9] )
decreasingTemp1=[9,7,6]     ( i.e temp[4:7] )
decreasingTemp2=[8,6,5,3,2] ( i.e temp[8:]  )

有没有办法做到这一点?

谢谢

猜猜这是一道典型的 LeetCode 数组题。我将遍历数组一次并为每个 increasing/decreasing 数字序列构建一个子数组。如果趋势的方向发生变化,我会检查子数组的长度是否至少为 n,然后将子数组添加到 increasing/decreasing 数组的列表中。

一个实现可能如下所示(O(n) 时间和内存)。

def return_arrays(arr,n):
    increasing = []
    decreasing = []
    new_arr = []
    for i,elem in enumerate(arr):
        if len(new_arr)>1:
            if new_arr[0]-new_arr[-1]>=0:
                # Decreasing
                if new_arr[-1]>=elem:
                    new_arr.append(elem)
                else:
                    if len(new_arr)>=n:
                        decreasing.append(new_arr)
                    new_arr = [new_arr[-1],elem]
            else:
                # Increasing
                if new_arr[-1]<=elem:
                    new_arr.append(elem)
                else:
                    if len(new_arr)>=n:
                        increasing.append(new_arr)
                    new_arr = [new_arr[-1],elem]
        else:
            new_arr.append(elem)
        if i==len(arr)-1:
            if len(new_arr)>=n:
                if new_arr[0]-new_arr[-1]>=0:
                    decreasing.append(new_arr)
                else:
                    increasing.append(new_arr)
    return increasing,decreasing 

将其应用于您的问题,您会得到以下输出:

temp = [4,5,7,8,9,7,6,7,8,6,5,4,3,2]
return_arrays(temp,3) # ([[4, 5, 7, 8, 9], [6, 7, 8]], [[9, 7, 6], [8, 6, 5, 4, 3, 2]])

希望对您有所帮助。如果要确保实现正确,您可能需要创建和检查更多测试用例。