Java diagonals' three-check solution


  • 0
    X
    public class Solution {
        public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
            //only three possible situations
            if (isPerpen(p1, p2, p3, p4) && isEqual(p1, p2, p3, p4) && isCenter(p1, p2, p3, p4)) return true;
            if (isPerpen(p1, p3, p2, p4) && isEqual(p1, p3, p2, p4) && isCenter(p1, p3, p2, p4)) return true;
            if (isPerpen(p1, p4, p2, p3) && isEqual(p1, p4, p2, p3) && isCenter(p1, p4, p2, p3)) return true;
            return false;
        }
        
       public boolean isPerpen (int[] p1, int[] p2, int[] p3, int[] p4) { //check whether two lines are perpendicular
           if ((p1[0] - p2[0]) * (p3[0] - p4[0]) + (p1[1] - p2[1]) * (p3[1] - p4[1]) == 0) return true;
           return false;
       }
        
       public boolean isEqual(int[] p1, int[] p2, int[] p3, int[] p4) {//check whether two lines' lengths are equal
           if (dist(p1, p2) == dist(p3, p4) && dist(p1, p2) != 0) return true;
           return false;
       }
       
       public boolean isCenter(int[] p1, int[] p2, int[] p3, int[] p4) {//check whether two lines' centers are equal
           if (p1[0] + p2[0] == p3[0] + p4[0] && p1[1] + p2[1] == p3[1] + p4[1]) return true;
           return false;
       }
        
       public int dist (int[] p1, int[] p2) {
           return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]);
       } 
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.