【算法练习】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 

你可能感兴趣的:(算法,算法,leetcode,职场和发展)