Java算法 leetcode简单刷题记录6

Java算法 leetcode简单刷题记录6

  1. 环和杆: https://leetcode.cn/problems/rings-and-rods/

  2. 统计范围内的元音字符串数: https://leetcode.cn/problems/count-the-number-of-vowel-strings-in-range/

  3. 最长平衡子字符串: https://leetcode.cn/problems/find-the-longest-balanced-substring-of-a-binary-string/

  4. K 个元素的最大和: https://leetcode.cn/problems/maximum-sum-with-exactly-k-elements/
    PriorityQueue优先取出最大值;

  5. 最长奇偶子数组: https://leetcode.cn/problems/longest-even-odd-subarray-with-threshold/
    根据题意写代码,所有条件true不好判断,可以先把false的返回;

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])) {
                return false;
            }
        }
        return true;
    }
}

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