-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathCheckSumOfSquareNumbers.java
89 lines (79 loc) · 2.16 KB
/
CheckSumOfSquareNumbers.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
Given a integer c, your task is to decide whether there're two integers a and b
such that a^2 + b^2 = c.
Example
Given n = 5
Return true // 1 * 1 + 2 * 2 = 5
Given n = -5
Return false
*/
public class CheckSumOfSquareNumbers {
/*
* @param : the given number
* @return: whether whether there're two integers
*/
public boolean checkSumOfSquareNumbers(int num) {
if (num < 0) {
return false;
}
int i = 0;
int j = (int) Math.sqrt(num);
while (i <= j) {
int sum = i * i + j * j;
if (sum == num) {
return true;
} else if (sum < num) {
i++;
} else {
j--;
}
}
return false;
}
/*****************************************************************************/
// TLE
public boolean checkSumOfSquareNumbers(int num) {
for (int i = 0; i * i <= num; ++i) {
int delta = num - i * i;
int sqrt = (int) Math.sqrt(delta);
if (sqrt * sqrt == delta) {
return true;
}
}
return false;
}
/*****************************************************************************/
// TLE
public boolean checkSumOfSquareNumbers(int num) {
if (num < 0) {
return false;
}
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i * i <= num; ++i) {
set.add(i * i);
if (set.contains(num - i * i)) {
return true;
}
}
return false;
}
/*****************************************************************************/
// OOM
public boolean checkSumOfSquareNumbers(int num) {
if (num < 0) {
return false;
}
boolean[] isSquare = new boolean[num + 1];
isSquare[0] = true;
for (int i = 1; i * i <= num; ++i) {
isSquare[i * i] = true;
}
for (int i = 0; i * i <= num; ++i) {
int delta = num - i * i;
if (isSquare[delta]) {
return true;
}
}
return false;
}
}