[LeetCode] 3152. Special Array II

CNoodle發表於2024-12-10

An array is considered special if every pair of its adjacent elements contains two numbers with different parity.

You are given an array of integer nums and a 2D integer matrix queries, where for queries[i] = [fromi, toi] your task is to check that subarray nums[fromi..toi] is special or not.

Return an array of booleans answer such that answer[i] is true if nums[fromi..toi] is special.

Example 1:
Input: nums = [3,4,1,2,6], queries = [[0,4]]
Output: [false]

Explanation:
The subarray is [3,4,1,2,6]. 2 and 6 are both even.

Example 2:
Input: nums = [4,3,1,6], queries = [[0,2],[2,3]]
Output: [false,true]

Explanation:
The subarray is [4,3,1]. 3 and 1 are both odd. So the answer to this query is false.
The subarray is [1,6]. There is only one pair: (1,6) and it contains numbers with different parity. So the answer to this query is true.

Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 105
1 <= queries.length <= 105
queries[i].length == 2
0 <= queries[i][0] <= queries[i][1] <= nums.length - 1

特殊陣列 II。

如果陣列的每一對相鄰元素都是兩個奇偶性不同的數字,則該陣列被認為是一個 特殊陣列 。

你有一個整數陣列 nums 和一個二維整數矩陣 queries,對於 queries[i] = [fromi, toi],請你幫助你檢查子陣列 nums[fromi..toi] 是不是一個 特殊陣列 。

返回布林陣列 answer,如果 nums[fromi..toi] 是特殊陣列,則 answer[i] 為 true ,否則,answer[i] 為 false 。

思路

思路是字首和。題目要我們判斷的不是子陣列的值,而是子陣列內是否存在特殊陣列。特殊陣列的定義是如果子陣列內每一對相鄰元素都是兩個奇偶性不同的數字,則該陣列被認為是一個特殊陣列。這道題利用字首和的方式很巧妙,我們建立一個與 input 陣列等長的字首和陣列,從 index = 1 那個數字開始,如果當前數字 nums[i - 1] 和 nums[i] 奇偶性不同,則 presum[i] = presum[i - 1] + 1,否則 presum[i] = presum[i - 1]。這裡 + 1 的用意是當我們用字首和去看某一段子陣列的值的時候,如果這一段子陣列的值大於 0,則說明這一段裡肯定有奇偶性不同的數字出現;如果這一段子陣列的值 == 0,則說明這一段裡沒有奇偶性不同的數字出現。

複雜度

時間O(n)
空間O(n)

程式碼

Java實現

class Solution {
    public boolean[] isArraySpecial(int[] nums, int[][] queries) {
        int n = nums.length;
        int[] presum = new int[n];
        for (int i = 1; i < n; i++) {
            presum[i] = presum[i - 1];
            if (helper(nums[i], nums[i - 1])) {
                presum[i]++;
            }
        }

        boolean[] res = new boolean[queries.length];
        for (int i = 0; i < queries.length; i++) {
            int left = queries[i][0];
            int right = queries[i][1];
            res[i] = presum[left] == presum[right];
        }
        return res;
    }

    private boolean helper(int a, int b) {
        if (a % 2 == b % 2) {
            return true;
        }
        return false;
    }
}

相關文章