注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
LC 593, 时间复杂度是O(1),因为只有四个点。
Follow up,给(n^2)呢- class Solution {
. 1point3acres.com - // Calculate each pair's distance
- // If distance ==0, return false
- // else put distance into a set
- // When finished, if set just contains 2 value
- // return true; else return false.google и
- public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
- // Tell if the point is valid
- // Put four points into a list
- List<int[]> list = new LinkedList<>();
- list.add(p1);
- list.add(p2);
- list.add(p3);
- list.add(p4);
- .
- for(int[] p : list){
- if(p == null || p.length != 2)
- return false;
- } ..
- Set<Integer> set = new HashSet<>();
- for(int i = 0; i < 3; i ++){
- for(int j = i + 1; j < 4; j ++){
- int[] px = list.get(i);.
- int[] py = list.get(j);
- int distance = calDistance(px, py);
- if(distance == 0)
- return false;
- set.add(distance);. 1point 3 acres
- }
- }
- return set.size() == 2;
- }
- private int calDistance(int[] p1, int[] p2){
- int x1 = p1[0], y1 = p1[1];
- int x2 = p2[0], y2 = p2[1];
- return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
- }
- // The follow up question is, given a series of point, tell number of squares.
- // First of all, tell if the list contains at least 4 points. 1point3acres.com
- public int validSquareII(List<int[]> list){
- if(list == null || list.size() < 4)
- return 0; ..
- int length = list.size();
- int result = 0;
- for(int i = 0; i < length - 3; i ++){
- for(int j = i + 1; j < length - 2; j ++){
- for(int k = j + 1; k < length -1; k ++){
- for(int l = k + 1; l < length; l ++){
- int[] p1 = list.get(i);
- int[] p2 = list.get(j);
- int[] p3 = list.get(k);
- int[] p4 = list.get(l);
- if (validSquare(p1,p2,p3,p4)){
- result ++;
- }
- }
- }.google и
- }
- }
- return result;
- } . 1point3acres.com
- }
复制代码 |