|
| 1 | +/** |
| 2 | + * 2013. Detect Squares |
| 3 | + * https://leetcode.com/problems/detect-squares/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a stream of points on the X-Y plane. Design an algorithm that: |
| 7 | + * - Adds new points from the stream into a data structure. Duplicate points are allowed and should |
| 8 | + * be treated as different points. |
| 9 | + * - Given a query point, counts the number of ways to choose three points from the data structure |
| 10 | + * such that the three points and the query point form an axis-aligned square with positive area. |
| 11 | + * |
| 12 | + * An axis-aligned square is a square whose edges are all the same length and are either parallel |
| 13 | + * or perpendicular to the x-axis and y-axis. |
| 14 | + * |
| 15 | + * Implement the DetectSquares class: |
| 16 | + * - DetectSquares() Initializes the object with an empty data structure. |
| 17 | + * - void add(int[] point) Adds a new point point = [x, y] to the data structure. |
| 18 | + * - int count(int[] point) Counts the number of ways to form axis-aligned squares with point |
| 19 | + * point = [x, y] as described above. |
| 20 | + */ |
| 21 | + |
| 22 | +var DetectSquares = function() { |
| 23 | + this.points = new Map(); |
| 24 | +}; |
| 25 | + |
| 26 | +/** |
| 27 | + * @param {number[]} point |
| 28 | + * @return {void} |
| 29 | + */ |
| 30 | +DetectSquares.prototype.add = function(point) { |
| 31 | + const [x, y] = point; |
| 32 | + const key = `${x},${y}`; |
| 33 | + this.points.set(key, (this.points.get(key) || 0) + 1); |
| 34 | +}; |
| 35 | + |
| 36 | +/** |
| 37 | + * @param {number[]} point |
| 38 | + * @return {number} |
| 39 | + */ |
| 40 | +DetectSquares.prototype.count = function(point) { |
| 41 | + const [x, y] = point; |
| 42 | + let result = 0; |
| 43 | + |
| 44 | + for (const [key, count] of this.points) { |
| 45 | + const [px, py] = key.split(',').map(Number); |
| 46 | + if (px === x || py === y || Math.abs(px - x) !== Math.abs(py - y)) continue; |
| 47 | + |
| 48 | + const point1 = `${x},${py}`; |
| 49 | + const point2 = `${px},${y}`; |
| 50 | + result += count * (this.points.get(point1) || 0) * (this.points.get(point2) || 0); |
| 51 | + } |
| 52 | + |
| 53 | + return result; |
| 54 | +}; |
0 commit comments