|
| 1 | + |
| 2 | +var DetectSquares = function() { |
| 3 | + this.xMap = new Map(); |
| 4 | + this.yMap = new Map(); |
| 5 | +}; |
| 6 | + |
| 7 | +/** |
| 8 | + * @param {number[]} point |
| 9 | + * @return {void} |
| 10 | + */ |
| 11 | +DetectSquares.prototype.add = function(point) { |
| 12 | + const [ x, y ] = point; |
| 13 | + |
| 14 | + // X-map |
| 15 | + if (this.xMap.has(x)) { |
| 16 | + const xMap = this.xMap.get(x); |
| 17 | + |
| 18 | + if (xMap.has(y)) { |
| 19 | + xMap.set(y, xMap.get(y) + 1); |
| 20 | + } else { |
| 21 | + xMap.set(y, 1); |
| 22 | + } |
| 23 | + } else { |
| 24 | + const countMap = new Map(); |
| 25 | + countMap.set(y, 1); |
| 26 | + this.xMap.set(x, countMap); |
| 27 | + } |
| 28 | + |
| 29 | + // Y-map |
| 30 | + if (this.yMap.has(y)) { |
| 31 | + const yMap = this.yMap.get(y); |
| 32 | + |
| 33 | + if (yMap.has(x)) { |
| 34 | + yMap.set(x, yMap.get(x) + 1); |
| 35 | + } else { |
| 36 | + yMap.set(x, 1); |
| 37 | + } |
| 38 | + } else { |
| 39 | + const countMap = new Map(); |
| 40 | + countMap.set(x, 1); |
| 41 | + this.yMap.set(y, countMap); |
| 42 | + } |
| 43 | +}; |
| 44 | + |
| 45 | +/** |
| 46 | + * @param {number[]} point |
| 47 | + * @return {number} |
| 48 | + */ |
| 49 | +DetectSquares.prototype.count = function(point) { |
| 50 | + const [ x, y ] = point; |
| 51 | + let ans = 0; |
| 52 | + |
| 53 | + if (this.xMap.has(x) && this.yMap.has(y)) { |
| 54 | + for (const y2 of this.xMap.get(x).keys()) { |
| 55 | + if (y === y2) { |
| 56 | + continue; |
| 57 | + } |
| 58 | + |
| 59 | + // Find parallel |
| 60 | + const sideLen = Math.abs(y - y2); |
| 61 | + const possibleX = [ x - sideLen, x + sideLen]; |
| 62 | + |
| 63 | + for (const px of possibleX) { |
| 64 | + if (this.yMap.get(y).has(px) && this.xMap.has(px) && this.xMap.get(px).has(y2)) { |
| 65 | + ans += this.xMap.get(x).get(y2) * this.yMap.get(y).get(px) |
| 66 | + * this.xMap.get(px).get(y2); |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + return ans; |
| 73 | +}; |
| 74 | + |
| 75 | +/** |
| 76 | + * Your DetectSquares object will be instantiated and called as such: |
| 77 | + * var obj = new DetectSquares() |
| 78 | + * obj.add(point) |
| 79 | + * var param_2 = obj.count(point) |
| 80 | + */ |
0 commit comments