中级农民
- 积分
- 155
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-4-17
- 最后登录
- 1970-1-1
|
写了下第一题code,
- public class RectanglesNumber {
- static class Point {
- int x;
- int y;
- public Point(int x, int y) {
- this.x = x;
- this.y = y;
- }
- }
- public static int getRectanglesNumber(int m, int n, Point[] points) {
- if (points == null || points.length == 0) {
- return 0;
- }
- HashMap<Integer, List<Point>> map = new HashMap<Integer, List<Point>>();
- for (Point p : points) {
- if (!map.containsKey(p.y)) {
- map.put(p.y, new ArrayList<Point>());
- }
- map.get(p.y).add(p);
- }
- HashMap<String, Integer> pairMap = new HashMap<String, Integer>();
- for (List<Point> list : map.values()) {
- for (int i = 0; i < list.size() - 1; i++) {
- for (int j = i + 1; j < list.size(); j++) {
- String key = list.get(i).x + "#" + list.get(j).x;
- if (pairMap.containsKey(key)) {
- pairMap.put(key, pairMap.get(key) + 1);
- } else {
- pairMap.put(key, 1);
- }
- }
- }
- }
- int res = 0;
- for (int val : pairMap.values()) {
- if (val > 1) {
- res += (val * (val - 1)) / 2;
- }
- }
-
- return res;
- }
-
- public static void main(String[] args) {
- Point[] points = {new Point(0, 1), new Point(0, 2), new Point(1, 0), new Point(1, 2), new Point(2, 0), new Point(2, 1), new Point(3, 0), new Point(3, 1), new Point(3, 2)};
- int res = getRectanglesNumber(3, 4, points);
- System.out.println(res);
- }
- }
复制代码 |
|