Given an array of integers, determine whether it contains a Pythagorean triplet. Recall that a Pythagorean triplet (a, b, c) is defined by the equation a^2 + b^2 = c^2.
Input: [1, 2, 3]
Output: false
Explanation: No three numbers in the array satisfy the Pythagorean theorem. 1^2 + 2^2 = 5, which is not equal to 3^2 = 9.
The simplest approach is to check all possible combinations of three numbers from the array and verify if they satisfy the Pythagorean theorem. For each triplet, we need to check if the sum of squares of two smaller numbers equals the square of the largest number.
classSolution {
publicbooleanhasPythagoreanTriplet(int[] nums) {
int n = nums.length;
if (n < 3) returnfalse;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
int[] triplet = {nums[i], nums[j], nums[k]};
Arrays.sort(triplet);
if (triplet[0]* triplet[0]+ triplet[1]* triplet[1]== triplet[2]* triplet[2]) {
returntrue;
}
}
}
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defhas_pythagorean_triplet(self, nums: List[int]) -> bool:
n = len(nums)
if n <3:
returnFalsefor i in range(n):
for j in range(i +1, n):
for k in range(j +1, n):
triplet = sorted([nums[i], nums[j], nums[k]])
if triplet[0]**2+ triplet[1]**2== triplet[2]**2:
returnTruereturnFalse
Instead of checking all triplets, we can optimize by fixing two numbers and checking if the third number (which would complete the Pythagorean triplet) exists in the array. We use a hash set for O(1) lookup.
classSolution {
publicbooleanhasPythagoreanTriplet(int[] nums) {
if (nums.length< 3) returnfalse;
Set<Integer> numSet =new HashSet<>();
for (int num : nums) {
numSet.add(num);
}
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
int a = nums[i], b = nums[j];
long cSquared = (long) a * a + (long) b * b;
int c = (int) Math.sqrt(cSquared);
if ((long) c * c == cSquared && numSet.contains(c)) {
returntrue;
}
}
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defhas_pythagorean_triplet(self, nums: List[int]) -> bool:
if len(nums) <3:
returnFalse num_set = set(nums)
for i in range(len(nums)):
for j in range(i +1, len(nums)):
a, b = nums[i], nums[j]
c_squared = a * a + b * b
c = int(c_squared **0.5)
if c * c == c_squared and c in num_set:
returnTruereturnFalse
We can sort the array and for each potential hypotenuse (largest value), use two pointers to find if there exist two numbers whose squares sum to the hypotenuse’s square. This approach leverages the sorted order to efficiently search for the pair.
classSolution:
defhas_pythagorean_triplet(self, nums: List[int]) -> bool:
if len(nums) <3:
returnFalse nums.sort()
for i in range(len(nums) -1, 1, -1):
left, right =0, i -1 target = nums[i] * nums[i]
while left < right:
current_sum = nums[left] * nums[left] + nums[right] * nums[right]
if current_sum == target:
returnTrueelif current_sum < target:
left +=1else:
right -=1returnFalse