@@ -50,15 +50,15 @@ edit_url: https://github.com/doocs/leetcode/edit/main/lcp/LCP%2061.%20%E6%B0%94%
50
50
51
51
<!-- solution:start -->
52
52
53
- ### 方法一:动态规划
53
+ ### 方法一:一次遍历
54
54
55
55
我们用变量 $f$ 维护当前趋势相同的连续天数,用变量 $ans$ 维护最大的连续天数。
56
56
57
57
遍历数组,对于第 $i$ 天,记两地的气温变化趋势分别为 $x$ 和 $y$,如果 $x$ 和 $y$ 均为 $0$ 或者 $x$ 和 $y$ 均为正数或负数,则说明第 $i$ 天和第 $i+1$ 天的气温变化趋势相同,此时 $f$ 自增 $1$,并更新 $ans$;否则说明第 $i$ 天和第 $i+1$ 天的气温变化趋势不同,此时 $f$ 重置为 $0$。
58
58
59
59
最终返回 $ans$ 即可。
60
60
61
- 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组长度 。
61
+ 时间复杂度 $O(n)$,其中 $n$ 为数组长度。 空间复杂度 $O(1)$。
62
62
63
63
<!-- tabs:start -->
64
64
@@ -68,10 +68,8 @@ edit_url: https://github.com/doocs/leetcode/edit/main/lcp/LCP%2061.%20%E6%B0%94%
68
68
class Solution :
69
69
def temperatureTrend (self , temperatureA : List[int ], temperatureB : List[int ]) -> int :
70
70
ans = f = 0
71
- n = len (temperatureA)
72
- for i in range (n - 1 ):
73
- x = temperatureA[i + 1 ] - temperatureA[i]
74
- y = temperatureB[i + 1 ] - temperatureB[i]
71
+ for (a1, b1), (a2, b2) in pairwise(zip (temperatureA, temperatureB)):
72
+ x, y = a2 - a1, b2 - b1
75
73
if x == y == 0 or x * y > 0 :
76
74
f += 1
77
75
ans = max (ans, f)
@@ -140,6 +138,51 @@ func temperatureTrend(temperatureA []int, temperatureB []int) int {
140
138
}
141
139
```
142
140
141
+ #### TypeScript
142
+
143
+ ``` ts
144
+ function temperatureTrend(temperatureA : number [], temperatureB : number []): number {
145
+ let [ans, f] = [0 , 0 ];
146
+ for (let i = 0 ; i < temperatureA .length - 1 ; ++ i ) {
147
+ let x = temperatureA [i + 1 ] - temperatureA [i ];
148
+ let y = temperatureB [i + 1 ] - temperatureB [i ];
149
+ if ((x === 0 && y === 0 ) || x * y > 0 ) {
150
+ ans = Math .max (ans , ++ f );
151
+ } else {
152
+ f = 0 ;
153
+ }
154
+ }
155
+ return ans ;
156
+ }
157
+ ```
158
+
159
+ #### Rust
160
+
161
+ ``` rust
162
+ impl Solution {
163
+ pub fn temperature_trend (temperature_a : Vec <i32 >, temperature_b : Vec <i32 >) -> i32 {
164
+ let mut ans = 0 ;
165
+ let mut f = 0 ;
166
+
167
+ for i in 0 .. temperature_a . len () - 1 {
168
+ let x = temperature_a [i + 1 ] - temperature_a [i ];
169
+ let y = temperature_b [i + 1 ] - temperature_b [i ];
170
+
171
+ if (x == 0 && y == 0 ) || (x > 0 && y > 0 ) || (x < 0 && y < 0 ) {
172
+ f += 1 ;
173
+ if f > ans {
174
+ ans = f ;
175
+ }
176
+ } else {
177
+ f = 0 ;
178
+ }
179
+ }
180
+
181
+ ans
182
+ }
183
+ }
184
+ ```
185
+
143
186
<!-- tabs: end -->
144
187
145
188
<!-- solution: end -->
0 commit comments