2013. Detect Squares

naive

At most 3000 calls in total will be made to add and count

ๆŠŠๆ‰€ๆœ‰้ปž้ƒฝๅŽป่ฉฆ่ฉฆ็œ‹ ๅ…ถไป–ไธ‰ๅ€‹้ปžๆ˜ฏๅฆๅญ˜ๅœจ, ่ถ…็ดš็ชฎ่ˆ‰, 3000*3000 => ็ˆ†็‚ธ

using x, y range, ๅฐ่ง’็ทš็š„ๆƒณๆณ•

  • 0 <= x, y <= 1000

  1. ้ฆ–ๅ…ˆ็ด€้Œ„ๆ‰€ๆœ‰้ปž

  2. count() ๆ™‚, ๆŠŠ input๏ผˆpoint[0], point[1]๏ผ‰็•ถไฝœ x, y ่ตท้ปž

(i, j) ๅฐ่ง’็ทš็š„้ปž, ๅ…ถไป–ๅ…ฉ้ปžๆœƒๆ˜ฏ...

for i to 1000
x = point[0], y =point[1]
d = abs(i - x)

so ไธŠๅฐ่ง’็ทš็š„้ปž: (i, j)
j = y+d               

i,j     [ x, j]

[i, y]    x,y


ไธ‹ๅฐ่ง’็ทš็š„้ปž: (i, j)
j = y-d               

[i, y]    x,y

i, j      [x, j]

ๅœจ x ่ปธไธŠ็ชฎ่ˆ‰ i = 0~1000 : ้‚ฃ่ท้›ข d = abs(i-x)

ๅˆฉ็”จ้€™ๅ€‹่ท้›ข

ๅŽป็ฎ—ๅฐ่ง’็ทš๏ผˆi, j๏ผ‰๏ผˆไธŠๅฐ่ง’็ทš, ไธ‹ๅฐ่ง’็ทš๏ผ‰, ็„ถๅพŒๅŽปๆ‰พๆ˜ฏไธๆ˜ฏๆœ‰็ฌฆๅˆ็š„ๅ…ถไป–ๅ…ฉๅ€‹้ปž

ๆ•ธ้‡ๅฐฑๆ˜ฏ้€™ไธ‰ๅ€‹้ปž็š„ๆ•ธ้‡ไน˜็ฉ

T: count: O(1000) , add: O(1)
S: O(1000*1000)
class DetectSquares {

    int[][] pCounts;
    public DetectSquares() {
        pCounts = new int[1001][1001];
    }
    
    public void add(int[] point) {
        pCounts[point[0]][point[1]]++;
    }
    
    public int count(int[] point) {
        int x = point[0];
        int y = point[1];
        int res = 0;
        for (int i = 0; i <= 1000; i++) {
            int dist = Math.abs(i - x);
            if (dist == 0) { // if ้ปž้‡ๅˆ pass
                continue;
            }
            
            int j = y + dist;
            if (j >= 0 && j <= 1000) {
                res += pCounts[i][j]*pCounts[x][j]*pCounts[i][y];
            }
            
            j = y - dist;
            if (j >= 0 && j <= 1000) {
                res += pCounts[i][j]*pCounts[x][j]*pCounts[i][y];
            }
        } 
        return res;
    }
}

/**
 * Your DetectSquares object will be instantiated and called as such:
 * DetectSquares obj = new DetectSquares();
 * obj.add(point);
 * int param_2 = obj.count(point);
 

for i to 1000
x = point[0], y =point[1]
d = abs(i - x)

so 
j = y+d               

i,j     [ x, j]

[i, y]    x,y


j = y-d               

[i, y]    x,y

i, j      [x, j]

T: count: O(1000) , add: O(1)
S: O(1000*1000)
 */

Last updated