ASMR LeetCode: Special Array II | Chill Coding

Поділитися
Вставка
  • Опубліковано 25 гру 2024

КОМЕНТАРІ • 1

  • @LeekCodeDev
    @LeekCodeDev  15 днів тому +1

    Source Code:
    class Solution:
    def isArraySpecial(self, nums: List[int], queries: List[List[int]]) -> List[bool]:
    '''
    To solve this problem, I'm first going to create an array 's'
    that has the same length as nums. I'm going to initialize every
    value in the array as 0, and update the values. What I'm going to
    update them, is basically each number in each index in the new
    array is going to represent the subarray number. So if I have
    in the array s: 0, 0, 0, 1 : This means that the first 3
    numbers in nums had different parity pairs, so they belonged
    to the same subarray, but the fourth element had the SAME
    parity, so it couldn't be together, so we start a new subarray
    by incrementing the previous subarray value. After finishing this,
    we look at queries in the format of [i,j] and just check if i and
    j have the same subarray number, because this would mean that
    they were valid throughout that range we were looking at. Otherwise,
    we return False :D
    '''
    res = []
    n = len(nums)
    s = [0] * n
    for i in range(1,n):
    if nums[i] % 2 != nums[i-1] % 2:
    s[i] = s[i-1]
    else:
    s[i] = s[i-1] + 1
    for i,j in queries:
    if s[i] == s[j]:
    res.append(True)
    else:
    res.append(False)
    return res