题解 | #直线上的牛#
直线上的牛
https://www.nowcoder.com/practice/58ff4047d6194d2ca4d80869f53fa6ec?tpId=354&tqId=10595661&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param points int整型二维数组
* @return int整型
*/
public int maxPoints (int[][] points) {
HashMap<Float, Integer> map = new HashMap<>();
int n = points.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
Float k = points[j][0] - points[i][0] == 0 ? null : (float) (
points[j][1] - points[i][1]) / (points[j][0] - points[i][0]);
map.put(k, map.getOrDefault(k, 0) + 1);
}
}
int res = 0;
for (int i : map.values()) {
res = Math.max(res, i);
}
return (int) (1 + Math.sqrt(1 + 8 * res)) / 2;
}
}
本题知识点分析:
1.哈希表的存取
2.数组遍历
3.数学模拟
本题解题思路分析:
1.计算两个点之间的斜率k。如果两个点的x坐标差为0,则斜率k设为null。否则,计算y坐标差除以x坐标差得到斜率k。
2.将斜率k作为key,并在HashMap中找到对应的点数值加1,如果没有找到则默认为0再加1。(API -> getOrDefault)
3.统计HashMap中的点数值的最大值,并将结果保存在变量res中。
4.返回点数值的最大值res的平方根加1再除以2。

OPPO成长空间 955人发布