Skip to content

Commit 5a2464f

Browse files
Add files via upload
1 parent 871c032 commit 5a2464f

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// 最暴力的方式就是n2的时间复杂度,但是可以用双指针加速到n的复杂度
2+
// 非常尴尬的是这样速度依然还是超时了,而且leftPtr如果使用int的话,也很容易发生溢出,因此需要使用long long
3+
class Solution
4+
{
5+
public:
6+
bool judgeSquareSum(int c)
7+
{
8+
// 边界条件处理
9+
if (c == 0 || c == 1)
10+
return true;
11+
12+
long long leftPtr = 0;
13+
long long rightPtr = c;
14+
long long res = c;
15+
16+
while (leftPtr <= rightPtr)
17+
{
18+
if ((leftPtr * leftPtr + rightPtr * rightPtr) > res)
19+
--rightPtr;
20+
else if ((leftPtr * leftPtr + rightPtr * rightPtr) < res)
21+
++leftPtr;
22+
else
23+
return true;
24+
}
25+
26+
return false;
27+
}
28+
};
29+
30+
31+
// 其实上边的思路是正确是,只要加上一个简单的trick就可以达到logn的时间复杂度,就是限制rightPtr的最大值
32+
// 所以这道题目最棒的一点就是需要考虑这个加速的小trick、以及使用更大的数据范围!!!!考察点还是非常棒的
33+
// Runtime: 0 ms, faster than 100.00% of C++ online submissions for Sum of Square Numbers.
34+
// Memory Usage: 8 MB, less than 100.00% of C++ online submissions for Sum of Square Numbers.
35+
36+
class Solution
37+
{
38+
public:
39+
bool judgeSquareSum(int c)
40+
{
41+
// 边界条件处理
42+
if (c == 0 || c == 1)
43+
return true;
44+
45+
long long leftPtr = 0;
46+
long long rightPtr = static_cast<int>(sqrt(c));
47+
long long res = c;
48+
49+
while (leftPtr <= rightPtr)
50+
{
51+
if ((leftPtr * leftPtr + rightPtr * rightPtr) > res)
52+
--rightPtr;
53+
else if ((leftPtr * leftPtr + rightPtr * rightPtr) < res)
54+
++leftPtr;
55+
else
56+
return true;
57+
}
58+
59+
return false;
60+
}
61+
};
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Runtime: 416 ms, faster than 15.92% of Python3 online submissions for Sum of Square Numbers.
2+
# Memory Usage: 13.8 MB, less than 50.00% of Python3 online submissions for Sum of Square Numbers.
3+
4+
import math
5+
6+
class Solution:
7+
def judgeSquareSum(self, c: int) -> bool:
8+
9+
if c is 0 or c is 1:
10+
return True
11+
12+
leftPtr = 0
13+
rightPtr = int(math.sqrt(c))
14+
15+
while leftPtr <= rightPtr:
16+
if leftPtr ** 2 + rightPtr ** 2 > c:
17+
rightPtr -= 1
18+
elif leftPtr ** 2 + rightPtr ** 2 < c:
19+
leftPtr += 1
20+
else:
21+
return True
22+
23+
return False

0 commit comments

Comments
 (0)