Java算法 leetcode简单刷题记录7

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/?

你可能感兴趣的:(算法,JAVA,算法,java,leetcode)