Skip to content

Files

Latest commit

b8e514b · Oct 29, 2022

History

History
174 lines (135 loc) · 3.81 KB

File metadata and controls

174 lines (135 loc) · 3.81 KB

English Version

题目描述

给你一个整数数组 nums 和一个整数 k ,请你统计并返回 nums 的子数组中元素的最大公因数等于 k 的子数组数目。

子数组 是数组中一个连续的非空序列。

数组的最大公因数 是能整除数组中所有元素的最大整数。

 

示例 1:

输入:nums = [9,3,1,2,6,3], k = 3
输出:4
解释:nums 的子数组中,以 3 作为最大公因数的子数组如下:
- [9,3,1,2,6,3]
- [9,3,1,2,6,3]
- [9,3,1,2,6,3]
- [9,3,1,2,6,3]

示例 2:

输入:nums = [4], k = 7
输出:0
解释:不存在以 7 作为最大公因数的子数组。

 

提示:

  • 1 <= nums.length <= 1000
  • 1 <= nums[i], k <= 109

解法

方法一:直接枚举

对于每个子数组,我们可以枚举其左右端点,计算出其最大公因数,然后判断是否等于 k 即可。

时间复杂度 O ( n 2 × l o g M ) ,其中 n M 分别是数组 nums 的长度和数组 nums 中的最大值。

Python3

class Solution:
    def subarrayGCD(self, nums: List[int], k: int) -> int:
        n = len(nums)
        ans = 0
        for i in range(n):
            x = nums[i]
            for j in range(i, n):
                x = gcd(x, nums[j])
                if x == k:
                    ans += 1
        return ans

Java

class Solution {
    public int subarrayGCD(int[] nums, int k) {
        int n = nums.length;
        int ans = 0;
        for (int i = 0; i < n; ++i) {
            int x = nums[i];
            for (int j = i; j < n; ++j) {
                x = gcd(x, nums[j]);
                if (x == k) {
                    ++ans;
                }
            }
        }
        return ans;
    }

    private int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }
}

C++

class Solution {
public:
    int subarrayGCD(vector<int>& nums, int k) {
        int n = nums.size();
        int ans = 0;
        for (int i = 0; i < n; ++i) {
            int x = nums[i];
            for (int j = i; j < n; ++j) {
                x = __gcd(x, nums[j]);
                ans += x == k;
            }
        }
        return ans;
    }
};

Go

func subarrayGCD(nums []int, k int) int {
	ans, n := 0, len(nums)
	for i, x := range nums {
		for j := i; j < n; j++ {
			x = gcd(x, nums[j])
			if x == k {
				ans++
			}
		}
	}
	return ans
}

func gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}

TypeScript

function subarrayGCD(nums: number[], k: number): number {
    const n = nums.length;
    let ans = 0;
    for (let i = 0; i < n; i++) {
        let x = nums[i];
        for (let j = i; j < n; j++) {
            x = gcd(nums[j], x);
            if (x == k) ans += 1;
        }
    }
    return ans;
}

function gcd(a: number, b: number): number {
    if (a > b) [a, b] = [b, a];
    if (a == 0) return b;
    return gcd(b % a, a);
}

...