当前位置:   article > 正文

Java | Leetcode Java题解之第149题直线上最多的点数

Java | Leetcode Java题解之第149题直线上最多的点数

题目:

题解:

  1. class Solution {
  2. public int maxPoints(int[][] points) {
  3. int n = points.length;
  4. if (n <= 2) {
  5. return n;
  6. }
  7. int ret = 0;
  8. for (int i = 0; i < n; i++) {
  9. if (ret >= n - i || ret > n / 2) {
  10. break;
  11. }
  12. Map<Integer, Integer> map = new HashMap<Integer, Integer>();
  13. for (int j = i + 1; j < n; j++) {
  14. int x = points[i][0] - points[j][0];
  15. int y = points[i][1] - points[j][1];
  16. if (x == 0) {
  17. y = 1;
  18. } else if (y == 0) {
  19. x = 1;
  20. } else {
  21. if (y < 0) {
  22. x = -x;
  23. y = -y;
  24. }
  25. int gcdXY = gcd(Math.abs(x), Math.abs(y));
  26. x /= gcdXY;
  27. y /= gcdXY;
  28. }
  29. int key = y + x * 20001;
  30. map.put(key, map.getOrDefault(key, 0) + 1);
  31. }
  32. int maxn = 0;
  33. for (Map.Entry<Integer, Integer> entry: map.entrySet()) {
  34. int num = entry.getValue();
  35. maxn = Math.max(maxn, num + 1);
  36. }
  37. ret = Math.max(ret, maxn);
  38. }
  39. return ret;
  40. }
  41. public int gcd(int a, int b) {
  42. return b != 0 ? gcd(b, a % b) : a;
  43. }
  44. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/737861
推荐阅读
相关标签
  

闽ICP备14008679号