classSolution {public:booljudgeSquareSum(intc) {longa =0, b =sqrt(c);while(a <=b) {if(a * a + b * b == c)returntrue;elseif(a * a + b * b < c) ++a;else--b; }returnfalse; } }; 下面这种解法基于费马平方和定理 Fermat's theorem
费马平方和定理 Fermat's theorem on sums of two squares的一般推广形式:当某个数字的 4k+3 型的质数因子的个数均为偶数时,其可以拆分为两个平方数之和(each prime that is congruent to 3 mod 4 appears with an even exponent in the prime factorization of the number)。那么我们只要统计其质数因子的个...
从0 和sqrt(n)两端分别查找 public boolean judgeSquareSum2(int c) { int low = 0; int high = (int)Math.sqrt(c); while(low<=high) { int sum = low*low+high*high; if(sum<c) { low++; } else if(sum>c) { high--; } else { return true; } } return false; } 1. 2. 3. 4...
https://leetcode.cn/problems/subarrays-distinct-element-sum-of-squares-ii 如果求的是“和”而不是“平方和”,那就和周赛291最后一题一样,连Hard都达不到。不过“平方和”问题就复杂很多,不但需要lazy线段树这一高级数据结构来做区间更新,而且有一定的数学成分,需要在维护区间平方和的同时,保证区间和也能够快...
public int numSquares(int n) { // four-square and three-square theorems. while (n % 4 == 0) n /= 4; if (n % 8 == 7) return 4; if (this.isSquare(n)) return 1; // enumeration to check if the number can be decomposed into sum of two squares. ...
isSquare(n)) return 1; // enumeration to check if the number can be decomposed into sum of two squares. for (int i = 1; i * i <= n; ++i) { if (this.isSquare(n - i * i)) return 2; } // bottom case of three-square theorem. return 3; } } 复杂度分析...
167. Two Sum II - Input array is sorted 977. Squares of a Sorted Array (很像merge sort里的...
leetcode最经典100题 以下是LeetCode的最经典的100题:1.两数之和(Two Sum)2.两数相加(Add Two Numbers)3.无重复字符的最长子串(Longest Substring Without Repeating Characters)4.寻找两个有序数组的中位数(Median of Two Sorted Arrays)5.最长回文子串(Longest Palindromic Substring)6. Z字形变换(ZigZag ...
给定一个含有 n 个正整数的数组和一个正整数 target 。 找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。 代码语言:javascript 代码运行次数:0 ...
0017 Letter Combinations of a Phone Number LeetCode 力扣 Python CSDN Medium 回溯、暴力 0034 Find First and Last Position of Element in Sorted Array LeetCode 力扣 Python CSDN Medium 二分 0039 Combination Sum LeetCode 力扣 Python CSDN Medium 回溯 0040 Combination Sum II LeetCode 力扣 Python CSDN...