1. Description
Given the coordinates of four points in 2D space, return whether the four points could construct a square.
The coordinate (x,y) of a point is represented by an integer array with two integers.
All the input integers are in the range [-10000, 10000].
A valid square has four equal sides with positive length and four equal angles (90-degree angles).
Input points have no order.
2. Runtime Distribution
3. Submission Details
4. Example
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: True
So the maximum integer in M is 2, and there are four of it in M. So return 4.
5. Code
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="Java" active="active"]
public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) { Mapmap = new HashMap (); map.put(distance(p1, p2), 1); double tmp = distance(p1, p3); map.put(tmp, map.getOrDefault(tmp, 0) + 1); tmp = distance(p1, p4); map.put(tmp, map.getOrDefault(tmp, 0) + 1); tmp = distance(p2, p3); map.put(tmp, map.getOrDefault(tmp, 0) + 1); tmp = distance(p2, p4); map.put(tmp, map.getOrDefault(tmp, 0) + 1); tmp = distance(p3, p4); map.put(tmp, map.getOrDefault(tmp, 0) + 1); return !map.containsKey(0.0) && map.values().size() == 2 && map.values().contains(4) && map.values().contains(2); } private double distance(int[] a, int[] b) { int diffX = a[0] - b[0]; int diffY = a[1] - b[1]; return Math.sqrt(diffX * diffX + diffY * diffY); }
[/restab]
[/restabs]
6.Test
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="Java" active="active" ]
import java.util.HashMap; import java.util.Map; public class LeetCode0593 { public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) { Mapmap = new HashMap (); map.put(distance(p1, p2), 1); double tmp = distance(p1, p3); map.put(tmp, map.getOrDefault(tmp, 0) + 1); tmp = distance(p1, p4); map.put(tmp, map.getOrDefault(tmp, 0) + 1); tmp = distance(p2, p3); map.put(tmp, map.getOrDefault(tmp, 0) + 1); tmp = distance(p2, p4); map.put(tmp, map.getOrDefault(tmp, 0) + 1); tmp = distance(p3, p4); map.put(tmp, map.getOrDefault(tmp, 0) + 1); return !map.containsKey(0.0) && map.values().size() == 2 && map.values().contains(4) && map.values().contains(2); } private double distance(int[] a, int[] b) { int diffX = a[0] - b[0]; int diffY = a[1] - b[1]; return Math.sqrt(diffX * diffX + diffY * diffY); } public static void main(String[] args) { int[] p1 = new int[] { 1, 0 }; int[] p2 = new int[] { -1, 0 }; int[] p3 = new int[] { 0, 1 }; int[] p4 = new int[] { 0, -1 }; LeetCode0593 leetcode = new LeetCode0593(); System.out.println(leetcode.validSquare(p1, p2, p3, p4)); } }
[/restab]
[/restabs]
Comments | NOTHING