0%

LeetCode-376

题目

Snipaste_2020-12-12_10-05-17.png

结果

Snipaste_2020-12-12_10-05-13.png

代码

统计极值数量(边界也要考虑)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
public int wiggleMaxLength(int[] nums) {
List<Integer> list = new ArrayList<>();
// 去重
for (int num : nums) {
if (list.isEmpty() || list.get(list.size() - 1) != num) {
list.add(num);
}
}

if (list.size() <= 2) {
return list.size();
}

// 极值数量
int cnt = 0;
for (int i = 0; i < list.size(); i++) {
if (isExtremum(list, i)) {
cnt++;
}
}
return cnt;
}

private boolean isExtremum(List<Integer> list, int index) {
// 处于边界
if (index == 0) {
return !list.get(1).equals(list.get(0));
} else if (index == list.size() - 1) {
return !list.get(list.size() - 1).equals(list.get(list.size() - 2));
}

int left = list.get(index - 1);
int mid = list.get(index);
int right = list.get(index + 1);
if (mid < left && mid < right) {
return true;
} else if (mid > left && mid > right) {
return true;
} else {
return false;
}
}
}

复杂度

时间复杂度:O(N)

空间复杂度:O(N)