zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 593 有效的正方形(判断正方形)

    593. 有效的正方形

    给定二维空间中四点的坐标,返回四点是否可以构造一个正方形。

    一个点的坐标(x,y)由一个有两个整数的整数数组表示。

    示例:

    输入: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
    输出: True

    注意:

    所有输入整数都在 [-10000,10000] 范围内。
    一个有效的正方形有四个等长的正长和四个等角(90度角)。
    输入点没有顺序。

    class Solution {
        public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
            // 判断标准:向量长度相等、垂直相交、对边平行,则为正方形
            // 先任意选两组进行判断,确定这两组的位置,是对角线还是对边
            int[] p1p2 = vector(p1, p2);
            int[] p3p4 = vector(p3, p4);
            
            // 长度
            if (getLength(p1p2) == 0) {
                return false;
            }
    
            // p1p2和p3p4:只能是垂直相交并且相等 或者 平行
            if (isVerticalAndLengthEqualVector(p1p2, p3p4)) {
                // p1p2, p3p4垂直 那么p1p3和p2p4必平行
                if (isParallelVector(vector(p1, p3), vector(p2, p4))) {
                    return true;
                }
            } else if (isParallelVector(p1p2, p3p4)){
                // p1p2, p3p4平行, 但确定不了方向,因此下面两组任意垂直且相等即可
                if (isVerticalAndLengthEqualVector(vector(p1, p4), vector(p2, p3)) ||
                        isVerticalAndLengthEqualVector(vector(p1, p3), vector(p2, p4))) {
                    return true;
                }
            }
    
            return false;
        }
        
        private int[] vector(int[] p1, int[] p2) {
            return new int[]{p1[0] - p2[0], p1[1] - p2[1]};
        }
    
        private double getLength(int[] p1p2) {
            return Math.sqrt(p1p2[0]*p1p2[0] + p1p2[1]*p1p2[1]);
        }
    
        private boolean isParallelVector(int[] p1, int[] p2) {
            return p1[0]*p2[1] == p1[1]*p2[0];
        }
    
        private boolean isVerticalAndLengthEqualVector(int[] p1, int[] p2) {
            return p1[0]*p2[0] + p1[1]*p2[1] == 0 && getLength(p1) == getLength(p2);
        }
    }
    
  • 相关阅读:
    Leetcode Plus One
    Leetcode Swap Nodes in Pairs
    Leetcode Remove Nth Node From End of List
    leetcode Remove Duplicates from Sorted Array
    leetcode Remove Element
    leetcode Container With Most Water
    leetcode String to Integer (atoi)
    leetcode Palindrome Number
    leetcode Roman to Integer
    leetcode ZigZag Conversion
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12946356.html
Copyright © 2011-2022 走看看