problem:
Difficulty: medium
Description:
Enter four arrays, each of which is an element of int[2] representing coordinate points, and then judge whether the coordinate points can be connected to form a square, and the input points are not sorted.
Subject link: https://leetcode.com/problems/valid-square/
Input range:
The point coordinate value will be in [-10000, 10000]
The four coordinate points must be at right angles
Enter the case:
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: True
My code:
Because the input of four arrays is mainly based on how to write the code to be concise, rather than writing like p1 p2 p3 p4, the code must be very long and ugly.
Fortunately, the coordinate value will not exceed the int range, and the four coordinates must be right angles, and then each point can be connected to three sides in a square shape, and there must be two equal adjacent sides and a long hypotenuse. I can use the ^ operation to exclude equal adjacent sides, and then see if it is equal to the longest side value to distinguish the rectangle, and judge whether it is 0 to eliminate the problem of the same point
class Solution {
public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
int[][] arr = new int[][]{p1, p2, p3, p4};
for(int i = 0;i < 4;i ++) {
int temp = 0, max = 0;
for(int j = 0;j < 4;j ++) {
if(i == j) continue;
int count = (int)Math.pow(arr[j][0] - arr[i][0], 2) + (int)Math.pow(arr[j][1] - arr[i][1], 2);
temp = Math.max(temp, count);
if(count == 0) return false; else max ^= count;
}
if(temp != max) return false;
}
return true;
}
}