LeetCode 149 JavaScript

241 阅读1分钟

思路

斜率会超出精度,需要特殊处理,看代码就懂

代码

/**
 * @param {number[][]} points
 * @return {number}
 */
var maxPoints = function(points) {
	function calSlope(deltaX, deltaY) { // 提供的 testcase 太大,超出精度范围
		const maxInt = 0xffffff;
		deltaY = deltaY % maxInt;
		deltaX = deltaX % maxInt;
		return deltaY / deltaX;
	}

	let len = points.length;
	if (len <= 2) {
		return len;
	}
	let max = 0;
	for (let i = 0; i < len - 1; ++i) {
		let rates = new Map();
		let allAll = 0;
		for (let j = i + 1; j < len; ++j) {
			const deltaY = points[j][1] - points[i][1];
			const deltaX = points[j][0] - points[i][0];
			if (deltaX === 0 && deltaY === 0) {
				allAll ++;
				continue;
			}
			let slope = calSlope(deltaY, deltaX);
			if (deltaX === 0) {
				slope = '竖线';
			} else if (deltaY === 0) {
				slope = '横线';
			}
			if (rates.has(slope)) {
				const val = rates.get(slope)
				rates.set(slope, val + 1);
			} else {
				rates.set(slope, 2);
			}
		}
		if (!rates.size) {
			max = Math.max(max, allAll + 1);
		} else {
			max = Math.max(max, ...([...rates.values()]).map(el => el + allAll));
		}
	}
	return max;
};