当前位置:网站首页>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)
边栏推荐
- 【一起上水硕系列】Day 8
- Fund valuation, expenses and accounting
- 25 interview questions about Apache
- 漫画安全HIDS、EDR、NDR、XDR
- LC: maximum subarray and
- Paper writing tool: latex online website
- Shell positional parameter variables and predefined variables
- 6.28 problem solving
- After working in the software development industry for six years, I changed my ideas in those years
- 雲和恩墨蓋國强,識別它、抓住它,在國產數據庫沸騰以前
猜你喜欢

采购数智化爆发在即,支出宝“3+2“体系助力企业打造核心竞争优势
![[wechat applet] understand the basic composition of the applet project](/img/71/98894fbb9cda4facfd2b83c8ec8f9a.png)
[wechat applet] understand the basic composition of the applet project

Overseas digital authentication service provider advance AI was selected into the "2022 brand sea Service Market Research Report" of equalocean

Sword finger offer 15 Number of 1 in binary

均值、方差、标准差、协方差的概念及意义

Simple understanding of B tree and b+ tree

InfluxDB时序数据库系统

声网自研传输层协议 AUT 的落地实践丨Dev for Dev 专栏

After crossing, she said that the multiverse really exists

HPE launched ARM CPU general server product
随机推荐
Implementation of aut, a self-developed transport layer protocol for sound network -- dev for dev column
Incluxdb time series database system
Sword finger offer 14- I. cut rope
Gradle连载7-配置签名
打造一个 API 快速开发平台,牛逼!
Halcon practical: design idea of solder joint detection
matlab习题 —— 程序控制流程练习
Halcon实用:焊点检出设计思路
C pointer advanced 2-- > function pointer array callback function simplifies calculator code, and implements qsort function based on callback function simulation
Leetcode(633)——平方数之和
On binary tree
Leetcode 1385. Distance value between two arrays
机器学习:VC维的概念和用途
I wonder if I can open an account today? In addition, is it safe to open an account online now?
Effective self summary of remote communication | community essay solicitation
[Shangshui Shuo series] day 8
FPGA Development (1) -- serial port communication
Procurement intelligence is about to break out, and the "3+2" system of Alipay helps enterprises build core competitive advantages
Sword finger offer 15 Number of 1 in binary
手机开户一般哪个证券公司好?另外,手机开户安全么?