活跃农民
- 积分
- 554
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-9-2
- 最后登录
- 1970-1-1
|
给一串数组代表坐标,求问这些坐标中能连成的长方形中,面积最大的那个是多大
假設長方行的邊皆與X軸或Y軸垂直或平行,不會有斜的長方形
- import java.util.*;
- public class RectangleMaxArea {
- public static void main(String[] args){
- Coordinate[] coordinates= new Coordinate[10];
- coordinates[0] = new Coordinate(-1,5);
- coordinates[1] = new Coordinate(-1,-3);
- coordinates[2] = new Coordinate(2,7);
- coordinates[3] = new Coordinate(2,3);
- coordinates[4] = new Coordinate(4,-1);
- coordinates[5] = new Coordinate(6,7);
- coordinates[6] = new Coordinate(6,3);
- coordinates[7] = new Coordinate(7,2);
- coordinates[8] = new Coordinate(2,-4);
- coordinates[9] = new Coordinate(6,-4);
- System.out.println(new RectangleMaxArea().getMaxArea(coordinates));
- }
- int getMaxArea(Coordinate[] coordinates){
- int maxArea = 0;
- Set<Coordinate> mySet = new HashSet<>();
- Collections.addAll(mySet,coordinates);
- if(mySet.size() < 4)
- return 0;
- int pointNum = coordinates.length;
- //we want to pick two diagonal points
- for(int i=0; i<pointNum; i++){
- for(int j=0; j<pointNum; j++){
- // if we pick two points with
- // 1. same coordinates or
- // 2. they are on the same vertical line or
- // 3. they are on the same horizontal line
- // we skip them because we want to pick diagonal point of the rectangle
- if(coordinates[i].equals(coordinates[j])
- || coordinates[i].x == coordinates[j].x
- || coordinates[i].y == coordinates[j].y)
- continue;
- int[] p1 = {coordinates[i].x, coordinates[i].y};
- int[] p2 = {coordinates[j].x, coordinates[j].y};
- int[] p3 = new int[2];
- int[] p4 = new int[2];
- if(mySet.contains(new Coordinate(p2[0],p1[1])) && mySet.contains(new Coordinate(p1[0],p2[1]))){
- p3[0] = p2[0];
- p3[1] = p1[1];
- p4[0] = p1[0];
- p4[1] = p2[1];
- maxArea = Math.max(maxArea,getArea(p1,p3,p4));
- }
- }
- }
- return maxArea;
- }
- int getArea(int[] p1, int[] p2, int[] p3){
- int edge1 = p1[0]-p2[0] + p1[1]-p2[1];
- int edge2 = p1[0]-p3[0] + p1[1]-p3[1];
- return edge1 * edge2;
- }
- }
- class Coordinate{
- int x;
- int y;
- Coordinate(int x, int y){
- this.x = x;
- this.y = y;
- }
- public boolean equals(Object p){
- Coordinate c = (Coordinate)p;
- return c.x == this.x && c.y == this.y;
- }
- public int hashCode(){
- final int prime = 997;
- return x + prime * y;
- }
- }
复制代码 |
|