Skip to content

Commit 1f202cd

Browse files
Merge pull request youngyangyang04#1207 from xiaofei-2020/greed03
添加(0376.摆动序列.md):增加typescript版本
2 parents c607ec0 + ee93d4d commit 1f202cd

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

problems/0376.摆动序列.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,5 +298,55 @@ var wiggleMaxLength = function(nums) {
298298
};
299299
```
300300

301+
### TypeScript
302+
303+
**贪心**
304+
305+
```typescript
306+
function wiggleMaxLength(nums: number[]): number {
307+
let length: number = nums.length;
308+
if (length <= 1) return length;
309+
let preDiff: number = 0;
310+
let curDiff: number = 0;
311+
let count: number = 1;
312+
for (let i = 1; i < length; i++) {
313+
curDiff = nums[i] - nums[i - 1];
314+
if (
315+
(preDiff <= 0 && curDiff > 0) ||
316+
(preDiff >= 0 && curDiff < 0)
317+
) {
318+
preDiff = curDiff;
319+
count++;
320+
}
321+
}
322+
return count;
323+
};
324+
```
325+
326+
**动态规划**
327+
328+
```typescript
329+
function wiggleMaxLength(nums: number[]): number {
330+
const length: number = nums.length;
331+
if (length <= 1) return length;
332+
const dp: number[][] = new Array(length).fill(0).map(_ => []);
333+
dp[0][0] = 1; // 第一个数作为波峰
334+
dp[0][1] = 1; // 第一个数作为波谷
335+
for (let i = 1; i < length; i++) {
336+
dp[i][0] = 1;
337+
dp[i][1] = 1;
338+
for (let j = 0; j < i; j++) {
339+
if (nums[j] < nums[i]) dp[i][0] = Math.max(dp[i][0], dp[j][1] + 1);
340+
}
341+
for (let j = 0; j < i; j++) {
342+
if (nums[j] > nums[i]) dp[i][1] = Math.max(dp[i][1], dp[j][0] + 1);
343+
}
344+
}
345+
return Math.max(dp[length - 1][0], dp[length - 1][1]);
346+
};
347+
```
348+
349+
350+
301351
-----------------------
302352
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
 (0)