According to the definition of Greatest Common Divisior, if m is any integer, then gcd(a + m * b, b) = gcd(a, b). Therefore, the gcd of (a + b, b), (a, a + b), (a - b, b) and (a, a - b) will be the same as the gcd of (a, b). Therefore, in order to move to the target point, the gcd of the target point should be equal to the gcd of the starting point.
1 2 3
publicbooleancanReach(int x1, int y1, int x2, int y2){ return gcd(x1, y1)== gcd(x2, y2); }
Leetcode 149. Max points on a line
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
* 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{ publicintmaxPoints(Point[] points){ // use O(n^2) to find all pair, store slope as key if(points == null) return0; int result = 0; // map: slope as key, count as val Map<String,Integer> map = new HashMap<>(); // loop over all points for(int i=0; i<points.length; ++i){ // check all lines with i and j // find max point on a line except i and overlap int max = 0, overlap = 0; map.clear(); for(int j=i+1; j<points.length; ++j){ // x,y pair as slope int x = points[j].x - points[i].x; int y = points[j].y - points[i].y; if(x == 0 && y == 0){ // points overlap overlap ++; continue; } int gcd = getGCD(x,y); // vertical and horizontal covered x /= gcd; y /= gcd; String key = x + "," + y; if(map.containsKey(key)) map.put(key,map.get(key)+1); else map.put(key,1); // max for one start point max = Math.max(max,map.get(key)); } // start point + other point on line + same as start result = Math.max(result,max+overlap+1); } return result; } privateintgetGCD(int a,int b){ return a == 0 ? b : getGCD(b%a,a); } }
近期评论