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; } } }
|