Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Leetcode 2447. Number of Subarrays With GCD Equal to K #145

Open
Woodyiiiiiii opened this issue Oct 23, 2022 · 0 comments
Open

Leetcode 2447. Number of Subarrays With GCD Equal to K #145

Woodyiiiiiii opened this issue Oct 23, 2022 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

这道题我一开始想用滑动窗口的方法去做,但写的时候想到,没有能够让左边界滑动的条件,再加上条件里数组长度并不是很长(暗示),所以放弃了此法(可以想到,遇到方法定式,要学会在关键处判断并及时转换思想)。

那么如果用O(n^2)的方法遍历所有子数组,那么如果计算子数组的最大公约数呢?虽然用Copilot提示过了,但细想下,最大公约数以最小的数为基准,每次增加一个数,最大公约数只可能变小,不会变大...

class Solution {
    public int subarrayGCD(int[] nums, int k) {
        
        int res = 0;
        int n = nums.length;

        for (int i = 0; i < n; i++) {
            if (nums[i] == k) {
                res++;
            }
            int gcd = nums[i];
            for (int j = i + 1; j < n; j++) {
                gcd = gcd(gcd, nums[j]);
                if (gcd == k) {
                    res++;
                }
            }
        }

        return res;
        
    }
    
    // 求最大公约数gcd
    public int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }
    
}

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant