149. Max Points on a Line

系统管理员 2021-12-22 06:55 289阅读 0赞
  1. class Solution {
  2. public int maxPoints(Point[] points) {
  3. if(points.length<3)
  4. return points.length;
  5. int res=0;
  6. Map<Integer, Map<Integer,Integer>> map=new HashMap<Integer, Map<Integer, Integer>>();
  7. for(int i=0;i<points.length;i++)
  8. {
  9. map.clear();
  10. int samepoint=1,max=0;
  11. for(int j=i+1;j<points.length;j++)
  12. {
  13. int x=points[i].x-points[j].x;
  14. int y=points[i].y-points[j].y;
  15. if(x==0&&y==0)
  16. samepoint++;
  17. else
  18. {
  19. int d=gcd(x,y);
  20. x/=d;
  21. y/=d;
  22. if (map.containsKey(x)){
  23. if (map.get(x).containsKey(y)){
  24. map.get(x).put(y, map.get(x).get(y)+1);
  25. }else{
  26. map.get(x).put(y, 1);
  27. }
  28. }else{
  29. Map<Integer,Integer> m = new HashMap<Integer,Integer>();
  30. m.put(y, 1);
  31. map.put(x, m);
  32. }
  33. max=Math.max(max, map.get(x).get(y));
  34. }
  35. res=Math.max(max+samepoint,res);
  36. }
  37. }
  38. return res;
  39. }
  40. private int gcd(int a, int b){
  41. if(b==0)
  42. return a;
  43. return gcd(b, a%b);
  44. }
  45. }

  

转载于:https://www.cnblogs.com/asuran/p/7679790.html

发表评论

表情:
评论列表 (有 0 条评论,289人围观)

还没有评论,来说两句吧...

相关阅读