Java算法 leetcode简单刷题记录7

23 篇文章 0 订阅

Java算法 leetcode简单刷题记录7

  1. 最长奇偶子数组: https://leetcode.cn/problems/longest-even-odd-subarray-with-threshold/

有的题看着不难,根据提示往下写,有的case就是死活过不了
这道题耗了挺久…

class Solution {
    public int longestAlternatingSubarray(int[] nums, int threshold) {
        int max = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int r = i; r < nums.length; r++) {
                if (isSatisfied(nums, threshold, i, r)) {
                    max = Math.max(r - i + 1, max);
                }
            }
        }
        return max;
    }

    private static boolean isSatisfied(int[] nums, int threshold, int l, int r) {
        if (nums[l] % 2 != 0) {
            return false;
        }
        for (int i = l; i <= r; i++) {
            if (nums[i] > threshold || (i < r && nums[i] % 2 == nums[i + 1] % 2)) {
                return false;
            }
        }
        if (l == r && nums[l] <= threshold) {
            return true;
        }
        return true;
    }
}
  1. 统计和小于目标的下标对数目: https://leetcode.cn/problems/count-pairs-whose-sum-is-less-than-target/
    直接写就行

  2. 爬楼梯: https://leetcode.cn/problems/climbing-stairs/

    递归或者 n+1的数组;
    n>=3时,f(n) = f(n-2) + f(n-1)

  3. 字典序最小回文串: https://leetcode.cn/problems/lexicographically-smallest-palindrome/

双指针俩边移动取最小的字符

class Solution {
    public String makeSmallestPalindrome(String s) {
        int left = 0;
        int right = s.length() - 1;
        char[] chars = s.toCharArray();
        while (left < right) {
            if (chars[left] < chars[right]) {
                chars[right] = chars[left];
            } else if (chars[left] > chars[right]) {
                chars[left] = chars[right];
            }
            ++left;
            --right;
        }
        return new String(chars);
    }
}
  1. 使用最小花费爬楼梯: https://leetcode.cn/problems/min-cost-climbing-stairs/

    动态规划

class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int[] dp = new int[cost.length+1];
        dp[0] = 0;
        dp[1] = 0;
        for(int i =2;i<=cost.length;i++){
            dp[i] = Math.min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2]);
        }
        return dp[cost.length];
    }
}
  1. 判别首字母缩略词: https://leetcode.cn/problems/check-if-a-string-is-an-acronym-of-words/?
  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序媛一枚~

您的鼓励是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值