【算法练习】leetcode算法题合集之其他篇
贪心算法
LeetCode376.摆动序列
LeetCode376.摆动序列
最后是向上幅度的摆动序列定义为
up
,最后是向下幅度的摆动序列定义为down
。如果数值相等,那么摆动序列的长度是不变的。
class Solution {
public int wiggleMaxLength(int[] nums) {
int n = nums.length;
if (n < 2) {
return n;
}
int[] up = new int[n];
int[] down = new int[n];
up[0] = down[0] = 1;
for (int i = 1; i < n; i++) {
if (nums[i] < nums[i - 1]) {
down[i] = up[i - 1] + 1;
up[i] = up[i - 1];
} else if (nums[i] > nums[i - 1]) {
up[i] = down[i - 1] + 1;
down[i] = down[i - 1];
} else {
up[i] = up[i - 1];
down[i] = down[i - 1];
}
}
return Math.max(up[n - 1], down[n - 1]);
}
}
缩维
class Solution {
public int wiggleMaxLength(int[] nums) {
int n = nums.length;
int up = 1;
int down = 1;
for (int i = 1; i < n; i++) {
if (nums[i] < nums[i - 1]) {
down = up + 1;
} else if (nums[i] > nums[i - 1]) {
up = down + 1;
}
}
return Math.max(up, down);
}
}
LeetCode55.跳跃游戏
LeetCode55.跳跃游戏
不断更新可以跳跃的位置,判断是否有大于等于
n-1
的索引。
class Solution {
public boolean canJump(int[] nums) {
int n = nums.length;
int coverage = 0;
for (int i = 0; i