/** * Definition for a point. * class Point { * int x; * int y; * Point() { x = 0; y = 0; } * Point(int a, int b) { x = a; y = b; } * } */ classSolution{ privateclassPCount{ Point point; int count = 1; publicPCount(Point point){ this.point = point; } } privateintGCD(int a, int b){ int c; while ( b != 0 ) { c = a % b; a = b; b = c; } return a; } publicintmaxPoints(Point[] points){ if ( points == null ) return0; int max = 0; PCount[] pcount = new PCount[points.length]; int pidx = 0; Map<String, Integer> ptable = new HashMap<>(); for ( Point point : points ) { String coord = point.x + "*" + point.y; Integer idx = ptable.get(coord); if ( idx == null ) { ptable.put(coord, pidx); pcount[pidx++] = new PCount(point); } else pcount[idx].count++; } if ( pidx == 1 ) return points.length; for ( int i = 0; i < pidx; i++ ) { Point p1 = pcount[i].point; Map<String, Integer> lines = new HashMap<>(); for ( int j = i + 1; j < pidx; j++ ) { Point p2 = pcount[j].point; String line = null; if ( p1.x == p2.x ) { line = "1/0"; } elseif ( p1.y == p2.y ) { line = "0/1"; } else { int denominator = p1.y - p2.y; int numerator = p1.x - p2.x; int gcd = GCD(denominator, numerator); if ( gcd != 0 ) { denominator /= gcd; numerator /= gcd; } line = denominator + "/" + numerator; } lines.put(line, lines.getOrDefault(line, pcount[i].count) + pcount[j].count); } for ( int count : lines.values() ) max = max < count ? count : max; } return max; } }
最大公约数
对于两个数A、B,求解它们的最大公约数。
方法一:
选出A、B中最小的数,向下一个一个进行取余,直到两个数的余数同时为0:
1 2 3 4 5 6 7
publicintGCD(int a, int b){ int c = a > b ? b : a; while ( a % c != 0 || b % c != 0 ) { c--; } return c; }