当前位置:网站首页>Leetcode (633) -- sum of squares
Leetcode (633) -- sum of squares
2022-06-29 23:51:00 【SmileGuy17】
Leetcode(633)—— Sum of squares
subject
Given a nonnegative integer c , You have to decide if there are two integers a and b, bring a 2 + b 2 = c a^2 + b^2 = c a2+b2=c.
Example 1:
Input :c = 5
Output :true
explain :1 * 1 + 2 * 2 = 5
Example 2:
Input :c = 3
Output :false
Tips :
- 0 0 0 <= c <= 2 31 − 1 2^{31 - 1} 231−1
Answer key
For a given nonnegative integer c c c, You need to determine whether there is an integer a a a and b b b, bring a 2 + b 2 = c a^2 + b^2 = c a2+b2=c. You can enumerate a a a and b b b All possible situations , The time complexity is O ( c 2 ) O(c^2) O(c2). But there are some situations where violence is unnecessary . for example : When c = 20 c = 20 c=20 when , When a = 1 a = 1 a=1 When , enumeration b b b When , Just enumerate to b = 5 b = 5 b=5 And that's it , This is because 1 2 + 5 2 = 25 > 20 1^2 + 5^2 = 25 > 20 12+52=25>20. When b > 5 b > 5 b>5 when , There must be 1 2 + b 2 > 20 1^2 + b^2 > 20 12+b2>20.
Take note of this , have access to sqrt \texttt{sqrt} sqrt Functions or double pointers reduce time complexity .
Method 1 : Using standard library functions sqrt \texttt{sqrt} sqrt
Ideas
In enumeration a a a At the same time , Use sqrt \texttt{sqrt} sqrt Function to find b b b. Be careful : This topic c c c The value range of is [ 0 , 2 31 − 1 ] [0,2^{31} - 1] [0,231−1], Therefore, in the process of calculation, it may happen int \texttt{int} int Type overflow , Need to use long \texttt{long} long Type to avoid overflow .
Code implementation
Leetcode Official explanation :
class Solution {
public:
bool judgeSquareSum(int c) {
for (long a = 0; a * a <= c; a++) {
double b = sqrt(c - a * a);
if (b == (int)b) {
return true;
}
}
return false;
}
};
Complexity analysis
Time complexity : O ( c ) O(\sqrt{c}) O(c). enumeration a a a The time complexity of is O ( c ) O(\sqrt{c}) O(c), For each a a a Value , Can be found in O ( 1 ) O(1) O(1) Time to find b b b
Spatial complexity : O ( 1 ) O(1) O(1)
Method 2 : Reverse double pointer
Ideas
No loss of generality , It can be assumed i ≤ m a x i \le max i≤max. At the beginning i = 0 i = 0 i=0, m a x = c max = \sqrt{c} max=c, Do the following :
- If m a x 2 + i 2 = c max^2 + i^2 = c max2+i2=c, We found a solution to the problem , return true \text{true} true;
- If m a x 2 + i 2 < c max^2 + i^2 < c max2+i2<c, At this time, we need to i i i The value of the add 1 1 1, Continue to find ;
- If m a x 2 + i 2 > c max^2 + i^2 > c max2+i2>c, At this time, we need to m a x max max The value of the reduction 1 1 1, Continue to find .
- When m a x = i max = i max=i when , Find the end , At this point, if the integer is still not found m a x max max and i i i Satisfy m a x 2 + i 2 = c max^2 + i^2 = c max2+i2=c, Then there is no solution required by the problem , return false \text{false} false.
As for the correctness of reverse double pointer traversing the sorted sequence ( That is, how to ensure that the correct answer is not missed ): You can refer to here .
So there are two issues to consider when using reverse double pointers : Each time the pointer is moved, what conditions are eliminated ? Are these situations likely to contain the correct answer ?
Code implementation
my :
class Solution {
public:
bool judgeSquareSum(int c) {
// Find out that the square root is less than or equal to c Maximum integer for max
int max = sqrt(c), i = 0;
while(i <= max){
// no need max*max + i*i and c Compare , Because type overflow may occur
if(c - max*max == i*i) return true;
c - max*max < i*i? max--: i++;
}
return false;
}
};
Complexity analysis
Time complexity : O ( c ) O(\sqrt{c}) O(c). In the worst case m a x max max and i i i A total of 0 0 0 To c \sqrt{c} c All integers in .
Spatial complexity : O ( 1 ) O(1) O(1)
Method 3 : mathematics
Ideas
Fermat's sum of squares theorem tells us :
A nonnegative integer c c c If it can be expressed as the sum of the squares of two integers , If and only if c c c All of the forms of 4 k + 3 4k + 3 4k+3 The powers of the prime factors of are even .
Certificate see here .
So we need to be right about c c c Do prime factor decomposition , Then judge all shapes such as 4 k + 3 4k + 3 4k+3 Whether the powers of the prime factors of are all even numbers .
Code implementation
Leetcode Official explanation :
class Solution {
public:
bool judgeSquareSum(int c) {
for (int base = 2; base * base <= c; base++) {
// If it's not a factor , Enumerate the next
if (c % base != 0) {
continue;
}
// Calculation base The power of
int exp = 0;
while (c % base == 0) {
c /= base;
exp++;
}
// according to Sum of two squares theorem verification
if (base % 4 == 3 && exp % 2 != 0) {
return false;
}
}
// for example 11 Such use cases , Because of the above for In circulation base * base <= c ,base == 11 It doesn't enter the circulation body
// Therefore, it is necessary to make another judgment after exiting the loop
return c % 4 != 3;
}
};
Complexity analysis
Time complexity : O ( c ) O(\sqrt{c}) O(c)
Spatial complexity : O ( 1 ) O(1) O(1)
边栏推荐
猜你喜欢

简单理解B树和B+树

Common knowledge of ECS security settings

FPGA Development (2) -- IIC communication

剑指 Offer 13. 机器人的运动范围

雲和恩墨蓋國强,識別它、抓住它,在國產數據庫沸騰以前

Yunhe enmo, gaiguoqiang, identify it and grasp it before the domestic database boils

How about counting Berry Pie 4? What are the possible ways to play?

Sword finger offer 13 Range of motion of robot

Et la tarte aux framboises 4? Quels sont les jeux possibles?
![[Shangshui Shuo series] day 8](/img/66/2aaa82f122612db1775bdd45556d97.png)
[Shangshui Shuo series] day 8
随机推荐
Cacti关于spine轮询的设置
Yunhe enmo, gaiguoqiang, identify it and grasp it before the domestic database boils
Solr basic operation 2
FPGA开发(2)——IIC通信
Solr基础操作1
Bee常用配置
Which securities company is good for opening a mobile account? In addition, is it safe to open a mobile account?
Solr basic operation 5
二叉树的序列化 力扣 297. 二叉树的序列化与反序列化 652. 寻找重复的子树
小程序插件接入、开发与注意事项
Jetpack之Room的使用,结合Flow
modelsim的TCL脚本的define incdir命令解析
招商证券靠谱吗?开股票账户安全吗?
开始“收割”!钉钉调整“钉钉Teambition”免费用人数上限,超十人将无法正常用
RRDtool 画MRTG Log数据
FPGA Development (2) -- IIC communication
Software testing interface testing JMeter 5.5 installation tutorial
xutils3传集合
Sword finger offer 38 Arrangement of strings
[LeetCode] 只出现一次的数字【136】