39
39
40
40
![ ] ( https://cdn.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0633.Sum%20of%20Square%20Numbers/images/table.png )
41
41
42
- 上图为 a,b,c 之间的关系,这题其实就是在这张“表”里查找 c
42
+ 上图为 a,b,c 之间的关系,这题其实就是在这张“表”里查找 c。
43
43
44
- 从表的右上角看,不难发现它类似一棵二叉查找树,所以只需从右上角开始,按照二叉查找树的规律进行搜索
44
+ 从表的右上角看,不难发现它类似一棵二叉查找树,所以只需从右上角开始,按照二叉查找树的规律进行搜索。
45
45
46
46
<!-- tabs:start -->
47
47
50
50
<!-- 这里可写当前语言的特殊实现逻辑 -->
51
51
52
52
``` python
53
- class Solution (object ):
54
- def judgeSquareSum (self , c ):
55
- i, j = 0 , int (math.sqrt(c))
56
- while i <= j:
57
- s = i * i + j * j
53
+ class Solution :
54
+ def judgeSquareSum (self , c : int ) -> bool :
55
+ a, b = 0 , int (sqrt(c))
56
+ while a <= b:
57
+ s = a** 2 + b** 2
58
+ if s == c:
59
+ return True
58
60
if s < c:
59
- i += 1
60
- elif s > c:
61
- j -= 1
61
+ a += 1
62
62
else :
63
- return True
63
+ b -= 1
64
64
return False
65
65
```
66
66
@@ -71,15 +71,16 @@ class Solution(object):
71
71
``` java
72
72
class Solution {
73
73
public boolean judgeSquareSum (int c ) {
74
- int i = 0 , j = (int ) Math . sqrt(c);
75
- while (i <= j) {
76
- int s = i * i + j * j;
74
+ long a = 0 , b = (long ) Math . sqrt(c);
75
+ while (a <= b) {
76
+ long s = a * a + b * b;
77
+ if (s == c) {
78
+ return true ;
79
+ }
77
80
if (s < c) {
78
- ++ i;
79
- } else if (s > c) {
80
- -- j;
81
+ ++ a;
81
82
} else {
82
- return true ;
83
+ -- b ;
83
84
}
84
85
}
85
86
return false ;
@@ -112,12 +113,13 @@ function judgeSquareSum(c: number): boolean {
112
113
class Solution {
113
114
public:
114
115
bool judgeSquareSum(int c) {
115
- long i = 0, j = (long) sqrt(c);
116
- while (i <= j) {
117
- long s = i * i + j * j;
118
- if (s < c) ++i;
119
- else if (s > c) --j;
120
- else return true;
116
+ long a = 0, b = (long) sqrt(c);
117
+ while (a <= b)
118
+ {
119
+ long s = a * a + b * b;
120
+ if (s == c) return true;
121
+ if (s < c) ++a;
122
+ else --b;
121
123
}
122
124
return false;
123
125
}
@@ -128,15 +130,16 @@ public:
128
130
129
131
```go
130
132
func judgeSquareSum(c int) bool {
131
- i, j := 0, int(math.Sqrt(float64(c)))
132
- for i <= j {
133
- s := i*i + j*j
133
+ a, b := 0, int(math.Sqrt(float64(c)))
134
+ for a <= b {
135
+ s := a*a + b*b
136
+ if s == c {
137
+ return true
138
+ }
134
139
if s < c {
135
- i++
136
- } else if s > c {
137
- j--
140
+ a++
138
141
} else {
139
- return true
142
+ b--
140
143
}
141
144
}
142
145
return false
0 commit comments